OC基础语法—@property和@synthesize使用
@property 和 @synthesize 和点方法类似,简化那些不必要的代码。只适用setter和getter,作用是让编译器自动生成setter和getter方法。@propety用在@interface 类的声明中,@synthesize 用在@implementation 类的实现中,举个例子:
@property int age; // 用这句代码就等价于下面两句,自动生成成员变量_age的setter方法和getter方法的申明
- (void)setAge:(int)age;
-(int)age;
@synthesize age=_age; // 用这句代码等价于下面两句,自动生产成员变量_age的setter方法和getter方法的实现
- (void)setAge:(int)age
{
_age=age;
}
-(int)age
{
return _age;
}
1.@ property的作用:
用在@inteface中
用来自动生成setter和getter的声明
用@property int age;就可以代替下面的两行
- (int)age; // getter
- (void)setAge:(int)age; // setter
2.@synthesize 的作用:
用在@implementation中
用来自动生成setter和getter的实现
用来自动生成setter和getter的实现
用@synthesize age = _age;就可以代替
- (int)age{
return _age;
}
- (void)setAge:(int)age{
_age = age;
}
其中 @synthesize age=_age; 这里的_age是成员变量,想对哪个变量进行访问就填哪个变量。
如果我们不定义成员变量,却还是让 @property 和 @synthesize 自动生成set和get方法,编译器并不会报错,而且会帮助我们生成这个没有定义的变量,但是类型是@private的。
@interface
@property int no;
@end
@implementation
@synthesize no=_no;
@end
这段代码中,没有去定义成员变量_no ,@property会自动帮我们生成一个@private _no 以供完成使用。
3.@ synthesize 使用注意:
1). @synthesize age = _age;
setter和getter实现中会访问成员变量_age
如果成员变量_age不存在,就会自动生成一个@private的成员变量_age
2).@ synthesizeage;
setter和getter实现中会访问成员变量age
如果成员变量age不存在,就会自动生成一个@private的成员变量age
3).手动实现
若手动实现了setter方法,编译器就只会自动生成getter方法
若手动实现了getter方法,编译器就只会自动生成setter方法
若同时手动实现了setter和getter方法,编译器就不会自动生成不存在的成员变量
在Xcode4.4以后,@synthesize可以省略不写,一个@property可以做三件事情,第一创建成员变量,第二生成set和get的声明,第三生成set和get的实现。
注意点:1.如果自己有定义成员变量或set和get方法,编译器不会再自动生成,优先读取自己定义的。
2.编译器自动生成的变量是@private类型,子类不能直接访问。
本文详细介绍了Objective-C中的@property和@synthesize指令的使用方法,包括如何用它们来简化setter和getter方法的声明与实现,以及一些重要的注意事项。

560

被折叠的 条评论
为什么被折叠?



