简体   繁体   中英

Should we declare properties' ivars or let the compiler do it for us? What about weak properties?

I'd like to understand if there is any advantage in declaring properties ivars instead of letting the compiler do it for us, considering only to build code for IOS5.. I think that the best practice should be not to declare them, otherwise you should remember of things like declaring ivars as __weak if the corresponding property is declared as weak.. it is necessary to do that, right? Otherwise the weak property is assigned to a strong ivar by default and it is no more weak...

I usually don't declare the ivar, and let it be done via the @property. However, in the @synthesize statement, I specify the name of the ivar to use for the implementation:

@interface MyClass
@property (weak) NSString* myString;
@end

@implementation MyClass
@synthesize myString = _myString;
@end

The = _myString in the @synthesize statement above is entirely optional, but it helps to force the distinction between accessing the ivar directly in your code and attempting to use the property accessors, because to use the ivar directly you have to type it out with the underscore. For example, you'll get a warning if you get lazy and try to do myString=@"xyz" , so you get a reminder to think about whether you meant to use self.myString or _myString . If you just had @synthesize myString without specifying a different ivar name, you wouldn't get a compiler warning in this case. Which could be a problem if you have implemented a custom setter method.

And this feels like a somewhat cleaner way to declare the ivars; you don't need to state the __weak modifier in this case, for example, as it's implied if you use this syntax.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM