I declared a property as below. From my readings on the web, it is not clear if I should also synthesize as below. I have seen supporting blog posts for two different approaches.
@property (assign, nonatomic) CGFloat someFloat;
Then in the implementation:
@synthesize someFloat = _someFloat;
I have also seen in some cases:
@synthesize someFloat;
From readings, I understand that “someFloat” is a property name, and “_someFloat” is created through the synthesis. So I am under the impression that the first way is correct. However, I have used the second approach without problems. And I have seen the second approach in other code and blogs.
Can someone tell me what is the correct way and why?
In general, you no longer need to manually write
@synthesizeanymore. In your example, if you writeThe compiler will automatically synthesize it for you, which would be equivalent to you writing
Hence, you would be able to access the property through
self.someFloator access the ivar within the implementation file by using_someFloat.If, however, you manually synthesize it like
The compiler automatically creates a backing ivar titled
someFloat… thereby, you would still be able to access the variable through the getterself.someFloat(that is, equivalent to[self someFloat]call).Or, you could access the ivar by simply using
someFloatsomewhere within the implementation…In general, it’s not recommended to synthesize like this because it’s quite easy to accidentally use the ivar when you meant to access the variable using the getter.
EXCEPTION TO THE RULE
The compiler still gets confused with synthesizing variables sometimes, however, in certain instances. For example, if you have a class that is a subclass of
NSManagedObject, then you still need to write the@synthesizemanually (assuming, of course, you actually want to synthesize the property… you likely don’t though…).The reason for this is two-fold: (1) the compiler doesn’t seem to understand these properties very well yet (or at least it doesn’t in the cases I’ve worked with), and (2) many times, you actually DON’T want to
@synthesizeproperties on anNSManagedObjectsubclass… rather, you want them to be@dynamicinstead (so the getter/setter will be generated at runtime, per requirements ofNSManagedObjectsubclass magic).