声明的属性是否需要相应的实例变量? [英] Do declared properties require a corresponding instance variable?

查看:95
本文介绍了声明的属性是否需要相应的实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C 2.0中的属性是否需要声明相应的实例变量?例如,我习惯做这样的事情:

Do properties in Objective-C 2.0 require a corresponding instance variable to be declared? For example, I'm used to doing something like this:

MyObject.h

@interface MyObject : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
@end

MyObject.m

@implementation
@synthesize name;
@end

但是,如果我改为这样做呢?

However, what if I did this instead:

MyObject.h

@interface MyObject : NSObject {
}
@property (nonatomic, retain) NSString *name;
@end

这仍然有效吗?并与我之前的示例有什么不同吗?

Is this still valid? And is it in any way different to my previous example?

推荐答案

如果使用的是Modern Objective-C运行时(iOS 3.x或更高版本,或者64位Snow Leopard或更高版本),则您<在这种情况下,strong>不需要需要为您的媒体资源定义Iva.

If you are using the Modern Objective-C Runtime (that's either iOS 3.x or greater, or 64-bit Snow Leopard or greater) then you do not need to define ivars for your properties in cases like this.

当您@synthesize该属性时,ivar实际上也将为您合成.这可以解决脆弱易变"方案.您可以在可可与爱中阅读有关此内容的更多信息

When you @synthesize the property, the ivar will in effect be synthesized also for you. This gets around the "fragile-ivar" scenario. You can read more about it on Cocoa with Love

这篇关于声明的属性是否需要相应的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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