首页 新闻 赞助 找找看

objective-c中实例变量和属性有什么区别

0
悬赏园豆:10 [已解决问题] 解决于 2012-08-27 10:31

在interface文件中用下面三种方法:
方法一:
@interface Application
{
UserInfo* userInfo;
ApplicationInfo*applicationInfo;
}

@property (retain) UserInfo*userInfo; // @synthesize userInfo;
@property (retain) ApplicationInfo* applicationInfo ; // @synthesize applicationInfo;
@end
方法二:
@interface Application
{
}

@property (retain) UserInfo*userInfo; // @synthesize userInfo;
@property (retain) ApplicationInfo* applicationInfo ; // @synthesize applicationInfo;
@end
方法三:
@interface Application
{
UserInfo* userInfo;
ApplicationInfo*applicationInfo;
}
@end


以上三种方法在implement中都可以使用 userInfo 和 applicationInfo,具体有什么区别?

bohan的主页 bohan | 初学一级 | 园豆:195
提问于:2012-08-25 13:44
< >
分享
最佳答案
0

1: This declares instance variables with accompanying declared properties. When you synthesise the properties, for example the property foo, the foo and setFoo methods are automatically generated which refer to the instance variables (due to having the same name), and these are called when you use dot notation (e.g. someInstance.foo = bar) to access them. Because you defined the properties to be retain, when you assign an object to the property using the setter or through dot notation, the existing object pointed to by the instance variable is released and the new object is assigned to the instance variable and retained.

2: Exactly the same as 1. The instance variables are implied.

3: The instance variables are there, but the properties are not, so you won't be able to access them through dot notation and no getter/setter methods are synthesised.

I strongly recommend reading the official documentation on this, it's quite clear and lays it all out in a fairly straightforward manner.

bohan | 初学一级 |园豆:195 | 2012-08-27 10:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册