前言
@property只能生成getter和setter方法的声明,那实现怎么办呢?
一、@synthesize是什么?
比如,有一个类
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *_name;
int _age;
float _weight;
}
@property NSString *name;
@property int age;
@property float weight;
@end
@implementation Person
@end
那么,getter和setter方法的实现,能不能自动生成呢?
1)@synthesize的作用:自动生成getter和setter方法的实现。
2)语法:@synthesize @property的名称;
例如:
@interface Person : NSObject
{
int _age;
}
@property int age;
@end
----------------------
@implementation Person
@synthesize age;
@end
二、@synthesize做的事情
1.生成一个真私有的属性
1) 什么叫真私有的属性,也就是声明在@implementation之中的,
2)这个属性的类型和@synthesize对应的@property类型一致;
3)属性的名字和@synthesize对应的@property名字一致;
例如,这段代码:
@implementation Person
@synthesize age;
@end
转换为
@implementation Person
{
int age;
}
- (void)setAge:(int)age;
{
self->age = age;
} - (int)age
{
return age;
}
@end
4)自动生成setter方法的实现
实现的方式:直接把参数age的值传递给它生成的那个私有属性age;
5)自动生成getter方法的实现
实现的方式:返回它自动生成的那个私有属性的值
2.如何让@synthesize不要自动生成私有属性,就用我们自己定义的带下划线的属性,就行了
语法:@synthesize @property名称 = 已经存在的属性名;
例如:@synthesize age = _age;
那么,这句话它是什么意思呢?
1)不再生成私有属性;
2)直接生成getter和setter方法的实现;
3)setter怎么实现的呢?把参数的值赋值给已经存在的下划线属性
例如:
- (void)setAge:(int)age
{
_age = age;
}
4)getter怎么实现的呢?直接返回已经存在的下划线属性的值。
- (int)age
{
return _age;
}
总结
使用@synthesize,有几点需要注意:
1)如果直接写1个@synthesize
例如:@synthesize name;
那么,它自动生成一个私有属性,并且操作的是自动生成的私有属性
2)如果指定操作的属性
例如:@synthesize name = _name;
那么,它就不会自动生成私有属性,并且操作的是我们指定的带下划线的属性;
3)生成的setter方法实现当中,是没有做任何逻辑验证的,是直接赋值。如果要实现逻辑验证,需要自己写setter方法的实现。例如:
- (void)setAge:(int)age
{
if(age >= 0 && age <= 120)
{
_age = age;
}
else
_age = 18;
}
4)批量声明
例如:
@property float height , weight;
如果多个@property的类型是一致的,可以批量声明;
@synthesize name, age, weight, height;
@synthesize name = _name,age=_age,weight=_weight,height= _height;
@synthesize类型不一致,也是可以批量声明的。
本文介绍了Objective-C中@synthesize的作用和实现方式,它用于自动生成getter和setter方法。@synthesize可以生成一个私有属性,或者指定操作已存在的属性。同时,文章提到了如何通过@synthesize实现逻辑验证和批量声明。
2878

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



