With the current version of Objective-C, what are the official standards and best practices for declaring ivars, using @property
and @synthesize
? There are a lot of posts and resources on the topic but most of them are fairly antiquated from a year or two ago. I recently learned to only declare ivars in a statement block in the implementation of a class so that the encapsulation principles of OOP aren't broken but is declaring ivars even necessary in this day and age? What would be a possible use case where doing:
@interface MyClass()
@property (nonatomic) NSString* data;
@end
@implementation MyClass{
@private
NSString* _data;
}
@end
is necessary? To further that, is it ever necessary to use @synthesize
? My understanding is that using @property
will auto-synthesize both the accessor methods as well as the backing ivars. I've done some experimentation and I noticed that when I don't declare NSString* _data', I can still access
_data' in my class implementation. Does that mean that declaring ivars come down to a matter of style, up to the discretion of the programmer? Could I condense my code and remove all ivar declarations in the statement blocks in my implementation and just use @property
in my private interface? If that's not the case, what are the advantages and disadvantages of explicitly declaring ivars?
Finally, @dynamic
. From what I can gather, it's used to say to the compiler, "Hey compiler, don't auto-generate the accessor method and don't worry if you don't find an implementation for it, I'll provide one at runtime". Is that all @dynamic
is used for or is there more to it?
I just want to clarify all these things because it seems like there's a lot of different opinions and that there's not necessarily one right answer. Plus as Objective-C grows and progresses, those answers will change so it'll be nice to have a concise and up-to-date guide. Thanks everyone! (Also if there's anything that I could word better or make clearer, let me know)
EDIT:
In summary, what I'm asking is this:
1) Is declaring ivars with modern Objective-C necessary?
2) Can I achieve the same effects of declaring ivars and corresponding properties by just using @property
?
3) What is @dynamic used for?
4) Can I completely forgo the use of @synthesize
or is there a good use case for it?
Upvote and down vote as you see fit.