readwrite/readonly
property中,getter又称read,setter又称write,readwrite/readonly这一组修饰词用来定制property的getter和setter合成,因此顾名思义:
- readwrite同时合成getter和setter
- readonly只合成getter,不合成setter
注:readwrite为默认值
@interface FBAnimal : NSObject
@property (readwrite) int age;
@property (readonly) UIColor *color;
@end
在interface中合成以下Method声明
@interface FBAnimal : NSObject
- (int)age;
- (void)setAge:(int)age
- (UIColor *)color;
@end
在implementation中合成以下Method定义
@implementation FBAnimal
{
int age;
UIColor *color;
}
- (int)age
{
//implement code
}
- (void)setAge:(int)age
{
//implement code
}
- (UIColor *)color
{
//implement code
}
@end
注:在readonly下,property只合成getter,此时getter就是property合成方法全部,如果implementation中显式定义property的getter,在synthesize下,仍会合成对应的数据成员(@synthesize显式合成),在auto synthesize下,不再合成对应的数据成员,编译器认为开发者要完全定制property(此时只有getter,没有setter),不再需要auto synthesize帮助
getter&setter
getter和setter修饰词用来定制property的getter和setter方法名以此代替getter和setter的默认合成方法名
默认合成方法名:
@interface FBAnimal : NSObject
@property int age;
@property UIColor *color;
@end
在interface中合成以下Method声明
@interface FBAnimal : NSObject
- (int)age;
- (void)setAge:(int)age
- (UIColor *)color;
- (void)setColor:(UIColor *)color;
@end
在implementation中合成以下Method定义
@implementation FBAnimal
{
int age;
UIColor *color;
}
- (int)age
{
//implement code
}
- (void)setAge:(int)age
{
//implement code
}
- (UIColor *)color
{
//implement code
}
- (void)setColor:(UIColor *)color
{
//implement code
}
@end
getter和setter修饰词定制property的getter和setter方法名:
@interface FBAnimal : NSObject
@property (getter=animalAge, setter=setAnimalAge:) int age;
@property (getter=animalColor, setter=setAnimalColor:) UIColor *color;
@end
注:setter修饰词定制setter方法名时不可omit默号(:),默号(:)表示setter带一个参数,显然getter和setter修饰词定制getter和setter的方法名即方法签名,而方法签名包括默号(:)
在interface中合成以下Method声明
@interface FBAnimal : NSObject
- (int)animalAge;
- (void)setAnimalAge:(int)age;
- (UIColor *)animalColor;
- (void)setAnimalColor:(UIColor *)color;
@end
在implementation中合成以下Method定义
@implementation FBAnimal
{
int age;
UIColor *color;
}
- (int)animalAge
{
//implement code
}
- (void)setAnimalAge:(int)age
{
//implement code
}
- (UIColor *)animalColor
{
//implement code
}
- (void)setAnimalColor:(UIColor *)color
{
//implement code
}
@end
注:getter和setter修饰词只是定制property的getter和setter方法签名,不会影响property合成的数据成员命名规则,即在上述property age和property color中,合成的数据成员名为_age和_color,而非_animalAge和_animalColor