1 使用属性

  • 接口代码简化 没有使用属性:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#import "Tire.h"

@interface AllWeatherRadial : Tire
{
    // 轮胎在潮湿和积雪的道路上的性能
    float rainHandling;
    float snowHandling;
}
- (void) setRainHandling:(float)rainHandling;
- (float) rainHandling;
- (void) setSnowHandling:(float)snowHandling;
- (float) snowHandling;
@end

使用属性:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@interface AllWeatherRadial : Tire
{
    // 轮胎在潮湿和积雪的道路上的性能
    float rainHandling;
    float snowHandling;
}

@property float rainHandling;
@property float snowHandling;

@end

@ property预编译指令的作用是自动声明属性的setter和getter方法。

  • 简化实现代码 之前:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#import "AllWeatherRadial.h"

@implementation AllWeatherRadial
-(NSString *)description
{
//    return (@"I am a tire for rain or shine.");
    NSString *desc;
    desc = [[NSString alloc] initWithFormat:@"AllWeatherRadial: %.1f / %.1f / %.1f / %.1f.", self.pressure, self.treadDepth, self.rainHandling, self.snowHandling];
    return desc;
}
- (void)setRainHandling:(float)r
{
    rainHandling = r;
}
- (float)rainHandling
{
    return rainHandling;
}
- (void)setSnowHandling:(float)s
{
    snowHandling = s;
}
- (float)snowHandling
{
    return snowHandling;
}

- (id) initWithPressure:(float)p treadDepth:(float)td
{
    if (self = [super initWithPressure:p treadDepth:td]) {
        rainHandling = 23.7;
        snowHandling = 58.1;
    }
    return self;
}
@end

使用属性后的实现代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#import "AllWeatherRadial.h"

@implementation AllWeatherRadial

@synthesize rainHandling;
@synthesize snowHandling;

-(NSString *)description
{
    NSString *desc;
    desc = [[NSString alloc] initWithFormat:@"AllWeatherRadial: %.1f / %.1f / %.1f / %.1f.", self.pressure, self.treadDepth, self.rainHandling, self.snowHandling];
    return desc;
}

- (id) initWithPressure:(float)p treadDepth:(float)td
{
    if (self = [super initWithPressure:p treadDepth:td]) {
        rainHandling = 23.7;
        snowHandling = 58.1;
    }
    return self;
}
@end

@synthesize预编译指令表示通知编译器生成访问方法。当遇到@synthesize xxx;这行代码时,编译器将添加实现-setXxx:和-xxx方法的预编译代码。

该@synthesize预编译指令不同于代码生成。你永远看不到实现-setXxx:和-xxx的代码,但是这些方法确实存在并可以被调用。这种技术使苹果公司可以更加灵活地改变Objective-C中生成访问方法的方式,并获得更安全的实现和更高的的性能。在Xcode4.5以后的版本中,可以不必使用@synthesize了。

  • 所有的属性都是基于变量的,在@synthesize时,编译器会自动创建与属性名称相同的实例变量。

    实例变量声明位置:

    • 头文件:有子类,想从子类直接通过属性访问变量。
    • 实现文件:变量只属于当前类。
  • 点表达式 之前的 [tire setPressure:23+i]; 可相应变为: tire.rainHandling = 23+i;

2 属性扩展

  • 实例变量和属性不是同一个名称
1
2
3
4
5
6
7
8
@interface Car : NSObject
{
    NSMutableArray *tires;
    Engine *engine;
    NSString *appellation;
}
@property (copy) NSString *name;
@property (retain) Engine *engine;

修改@synthesize指令为: @synthesize name = appellation; 编译器仍将创建-setName:-name方法,但在其实现代码中用的确实appellation实例变量。

  • 只读属性 readwrite readonly 属性为只读时,编译器只会生成一个getter方法。

  • 属性不支持那些需要接收额外参数的方法。如car对象中tire对象的代码。