特性(property)是Object-C 中组合了新的预编译指令和新的属性的访问器语法。新的特性功能显著减少了必须编写的冗长代码的数量。
//老代码
@interface allWeatherRadial:Tirl{
float rainHandling;
float snowHandling;
}
-(void ) setRainHandling:(float )rainHandling;
-(float )rainHandling;
-(void ) setSnowHandling:(float )rainHandling;
-(float )snowHandling;
@end
//改为特性风格的代码
#import<Foundation/Foundation.h >
#import Tirl;
@interface allWeatherRadial:Tirl{
float rainHandling;
float snowHandling;
}
@property float rainHandling;//表明AllWeatherRadial类的对象具有float类型的属性,其名称为rainHandling.
@property float snowHandling;
@end
@property预编译指令的作用是自动声明属性的setter和getter方法。
还有其他的特性,如:
@synthesize 也是一种新的编译器功能,表示“创建该属性的访问器”。档遇到代码@synthesize rainHandling;编译器将输出-setRainHandling:和-rainHandling 方法的已编译的代码。
默认情况下,特性可修改:既可读入也可以写入。使用特性的readwrite属性,如:
@property (readwrite ,copy) NSString *name;//可明确表达自己的意图,通常不需要
<span style="font-family: Arial, Helvetica, sans-serif;">@property (readwrite ,copy) Engine *engine;</span>
也可以是只读属性:
@property (readonly) float shoeSize ;//只读属性,则编译器只为该属性生成一个getter方法。
注意:特性不支持那些需要接受额外参数的方法。