我们应该声明属性'ivars还是让编译器为我们做?弱势属性怎么样? [英] Should we declare properties' ivars or let the compiler do it for us? What about weak properties?

查看:115
本文介绍了我们应该声明属性'ivars还是让编译器为我们做?弱势属性怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解是否有任何优势来声明属性ivars而不是让编译器为我们做,只考虑为IOS5构建代码。我认为最好的做法不应该是声明它们,如果相应的属性被声明为弱,你应该记住将ivars声明为__weak的事情。有必要这样做,对吧?否则,弱属性默认分配给强大的ivar并且不再弱...

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

推荐答案

我通常不会t声明ivar,并通过@property完成。但是,在@synthesize语句中,我指定了用于实现的ivar的名称:

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

= _myString 上面的@synthesize语句中的>是完全可选的,但它有助于强制区分直接在代码中访问ivar和尝试使用属性访问器,因为直接使用ivar,您必须使用下划线键入它。例如,如果你变懒并且尝试做 myString = @xyz,你会收到警告,所以你得到一个提醒,想一想你是否打算使用 self.myString _myString 。如果您只是 @synthesize myString 而未指定其他ivar名称,则在这种情况下您将不会收到编译器警告。如果你已经实现了一个自定义的setter方法,那么这可能是一个问题。

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.

这感觉就像是一种更简洁的方式来声明ivars;在这种情况下,您不需要声明 __ weak 修饰符,例如,如果您使用此语法则暗示它。

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.

这篇关于我们应该声明属性'ivars还是让编译器为我们做?弱势属性怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆