Say I have a class like this:
@interface MyAwesomeClass : NSObject
{
@private
NSString *thing1;
NSString *thing2;
}
@property (retain) NSString *thing1;
@property (retain) NSString *thing2;
@end
@implementation MyAwesomeClass
@synthesize thing1, thing1;
@end
When accessing thing1
and thing2
internally (i.e, within the implementation of MyAwesomeClass
), is it better to use the property, or just reference the instance variable directly (assuming cases in which we do not do any work in a "custom" access or mutator, i.e., we just set and get the variable). Pre-Objective C 2.0, we usually just access the ivars directly, but what's the usual coding style/best practice now? And does this recommendation change if an instance variable/property is private and not accessible outside of the class at all? Should you create a property for every ivar, even if they're private, or only for public-facing data? What if my app doesn't use key-value coding features (since KVC only fires for property access)?
I'm interested in looking beyond the low-level technical details. For example, given (sub-optimal) code like:
@interface MyAwesomeClass : NSObject
{
id myObj;
}
@proprety id myObj;
@end
@implementation MyAwesomeClass
@synthesize myObj;
@end
I know that myObj = anotherObject
is functionally the same as self.myObj = anotherObj
.
But properties aren't merely fancy syntax for instructing the compiler to write accessors and mutators for you, of course; they're also a way to better encapsulate data, i.e., you can change the internal implementation of the class without rewriting classes that rely on those properties. I'm interested in answers that address the importance of this encapsulation issue when dealing with the class's own internal code. Furthermore, properly-written properties can fire KVC notifications, but direct ivar access won't; does this matter if my app isn't utilizing KVC features now, just in case it might in the future?