Should we declare properties' ivars or let the

2019-09-09 09:04发布

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...

1条回答
等我变得足够好
2楼-- · 2019-09-09 09:54

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.

查看更多
登录 后发表回答