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 @synthesize
anymore. In your example, if you write
@property (assign, nonatomic) CGFloat someFloat;
The compiler will automatically synthesize it for you, which would be equivalent to you writing
@synthesize someFloat = _someFloat;
Hence, you would be able to access the property through self.someFloat
or access the ivar within the implementation file by using _someFloat
.
If, however, you manually synthesize it like
@synthesize someFloat;
The compiler automatically creates a backing ivar titled someFloat
... thereby, you would still be able to access the variable through the getter self.someFloat
(that is, equivalent to [self someFloat]
call).
Or, you could access the ivar by simply using someFloat
somewhere 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 @synthesize
manually (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 @synthesize
properties on an NSManagedObject
subclass... rather, you want them to be @dynamic
instead (so the getter/setter will be generated at runtime, per requirements of NSManagedObject
subclass magic).
只需跳过@synthesize
语句,编译器将生成与您具有相同的内容:
@synthesize someFloat = _someFloat;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.