Objective-C: Making iVars @public or @synthesizing @properties for them? When should I use properties?
-
13-11-2019 - |
문제
I have some instance variables in my class that I'd want to be accessible anywhere. Like so:
@interface SomeObject : NSObject
{
@public
NSString *someString;
}
@end
@implementation SomeObject
@end
I can access the property from the instance using the ->
syntax like below, as I would do in C++:
someObjectInstance->someString
Should I make a property for someString
when all I want is for it to be accessible by the outside world? I would create a @property
for someString
in my interface and @synthesize
it in my implementation, which would enable me to access it using the dot syntax.
해결책
Generally speaking, if you want to expose data, you should use properties. Making instance variables public is a bad idea in general.
다른 팁
It's the more object-oriented way to do it because when using a property you can change the getter/setter later (instead of having it synthesized) if you wanted it to do something else.
Yes, because what you're doing when you make it a @property
is directing folks using it to call the setSomeString
and someString
methods, in effect. Even if you're @synthesize
ing them, it's better for your code quality to be using the methods, because you could change them if you need to. If you're just using the pointer reference, if you find yourself needing to intercept accesses you won't be able to.