一、@property和@synthesize
在类的声明中我们会写一大堆的成员变量和成员变量对应的get、set方法,在类的实现中我们还需要将类的set、get方法进行实现,但是无论是类的声明还是类的实现,很多代码都是类似的,所有成员变量的set方法都是类似的,所有get方法又是相似的,所以我们在写代码的时候发现很多工作都是没有技术含量的,代码很多,但是完成的功能都是一样的。所以苹果公司为了减少程序员的这些没有技术含量的工作,让程序员将精力放在程序的功能上,苹果公司提供了property和@synthesize。@property:翻译:所有者
@synthesize:翻译:合成、综合
二、@property和@synthesize的应用示例:
//一般的类的声明: @interface Person : NSObject { int _age; int _weight; int _height; } - (void)setAge:(int)age; - (int)age; - (void)setWeight:(int)weight; - (int)weight; - (void)setHeight:(int)height; - (int)height; @end //应用@property的声明:(等同于上面的声明) @interface Person : NSObject @property int age; @property int weight; @property int height; @end
//一般的类的实现: @implementation Person - (void)setAge:(int)age { _age = age; } - (int)age { return age; } - (void)setWeight:(int)weight { _weight = weight; } - (int)weight { return weight; } - (void)setHeight:(int)height { _height = height; } - (int)height { return _height; } @end //应用@synthesize的类的实现(等同于上面的实现): @implementation Person @synthesize age = _age; @synthesize weight = _weight; @synthesize height = _height; @end
三、@property和@synthsize解析
1、 @property和@synthsize的这种作用是编译器的特性,当编译器遇到@property和@synthsize时就会自动将代码进行转化:
2、 @property的作用:可以自动生成某个成员变量的getter和setter的声明,由左边自动转化为右边代码:@property int age; <==> - (void)setAge:(int)age;
3、 @synthesize的作用:可以自动实现getter和setter;- (int)age;
@synthesize age = _age; <==> - (void)setAge:(int)age
@synthesize char * name; <==> - (void)setName:(char *)name //编译器会自动生成一个@private的name变量{
_age = age;
}
- (int)age
{
return _age;
}
{
name = name;
}
- (int)name
{
return name;
}