I’m trying to understand how strategies some folks use to distinguish instance vars vs. properties. A common pattern is the following:
@interface MyClass : NSObject { NSString *_myVar; } @property (nonatomic, retain) NSString *myVar; @end @implementation MyClass @synthesize myVar = _myVar;
Now, I thought the entire premise behind this strategy is so that one can easily distinguish the difference between an ivar and property. So, if I want to use the memory management inherited by a synthesized property, I’d use something such as:
myVar = @'Foo';
The other way would be referencing it via self.[ivar/property here].
The problem with using the @synthesize myVar = _myVar strategy, is I figured that writing code such as:
myVar = some_other_object; // doesn't work.
The compiler complains that myVar is undeclared. Why is that the case?
Thanks.
Properties are just setters and getters for
ivarsand should (almost) always be used instead of direct access.@synthesizecreates in this case those two methods (not 100% accurate):It’s easy now to distinguish between
ivarsand getters/setters. The accessors have got theself.prefix. You shouldn’t access the variables directly anyway.Your sample code doesn’t work as it should be: