Reputation: 12596
I am learning Objective-C and was just curious. I can create an object of a NSString
in these places, and please provide any others. To me they all do the same thing. I don't know what is the difference is between them. Where is it stored? From where can I access it? What are the advantages?
1)
// .h
@interface ...
@property (strong,nonatomic) NSString *text;
@end
2)
// .h
@interface ... {
NSString *text
}
@end
3)
// .m
@interface ... ()
@property (strong,nonatomic) NSString *text;
@end
Upvotes: 0
Views: 163
Reputation: 9231
First and foremost, my answer is based on the latest Clang compiler, older versions worked slightly different.
So, you're not creating an object in neither. You're not even declaring an object in two of them.
In the first case, you're actually telling the compiler that you need to expose a property called text
of type NSString
. What the compiler does, is declaring an instance variable for you _text
(which you can access without a problem by the way) and the methods needed to get and set that instance variable. As you can see the storage is still internal, you just have getters and setters set for you.
In the second case you're actually declaring an instance variable (ivar) yourself, just as the compiler does with _text
. It's accustom to prefix it with _
. The storage is still internal. On top of that, you can't access your ivar from outside, since it has no getter or setter and the implicit declaration is @private
.
In the third case, you create an anonymous category (thus the empty parentheses) which adds a property to your class. Storage for this is a little bit harder/longer to explain, if you are curious about it, you can search up the Apple docs, see what a category is and so on. You can only access your property from within your class in this case, which makes it somehow redundant (the getters and setters), you could have declared it as an ivar.
You can also declare your ivars like this:
@interface GenericViewController : UIViewController{
NSString * text;
}
@end
@implementation GenericViewController{
NSString * text;
}
@end
Both of the above have local storage and private visibility (can't be accessed from outside). The difference between the two is that instance variables declared in the implementation are implicitly hidden and the visibility cannot be changed with @public, @protected and @private. If you use those directives you won't get compiler errors but are ignored.
Upvotes: 1