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了。
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
实例变量。
文章作者
andyron
上次更新
2024-07-16
许可协议
原创文章,如需转载请注明文章作者和出处。谢谢!