@property
属性其实是对成员变量的一种封装。我们先大概这样理解:
@property = Ivar + setter + getter
Ivar
Ivar可以理解为类中的一个变量,主要作用是用来保存数据的。
==========================================================
我们不妨来看个例子,通过下边的例子能够很清楚的解释这两个东东:
我们新建一个Person
类
@interface Person : NSObject
{
NSString *name0;
}
@property(nonatomic,copy)NSString *name1;
@end
@implementation Person
- (instancetype)init {
if (self = [super init]) {
}
return self;
}
@end
在这个Person
中<font color=red>name0</font>就是成员变量,<font color=red>name1</font>就是属性。
我们创建一个Person
:
Person *p= [[Person alloc] init];
p.name1 = @"abc";
NSLog(@"%@",p.name1);
我们会发现,我在Person
类外边是不能访问<font color=red>name0</font>的,这说明了什么?这说明成员变量name0只能在它自己的类的内部被访问。
当然若想实现成员变量也支持外部访问,需要给该成员变量添加@public修饰符,在外部访问时,使用->来访问。
因此,我们推断出,@property其实也带有接口属性,也就是能够被外部对象访问。
p.name1 = @"abc";
这行代码其实是调用了Person
中<font color=red>name1</font>的setter方法。
NSLog(@"%@",p.name1);
这行代码其实是调用了Person
中<font color=red>name1</font>的getter方法。
再说说setter和getter方法。大家应该都知道oc中有着严格的命名规范,拿这个例子来说,根据<font color=red>name1</font>自动生成了
- (void)setName1:(NSString *)name1{}
- (NSString *)name1
<font color=red>注意:这里并不讨论MRC的情况,一切解释的前提都是在ARC下。</font>
@synthesize
这个关键字用来指定成员变量
我们在Person
的实现中,把代码改成这样:
@implementation Person
@synthesize name1 = _name2;
- (instancetype)init {
if (self = [super init]) {
_name2 = @"aaa";
}
return self;
}
@end
这样我们就指定了<font color=red>name1</font>的成员变量为<font color=red>_name2</font>了,我们在Person
的初始化init方法中根本打不出<font color=red>_name1</font>这个属性。
Person *p= [[Person alloc] init];
// p.name1 = @"abc";
NSLog(@"%@",p.name1);
我们注释掉赋值的那一行,可以看到打印结果为:aaa。
** 好了,这篇只是简单的讲了下property和ivar的区别,如有错误,还请指正。 **
网友评论