本節重點理解 @property 到底替我們做了什麼,並演示自定義初始化方法。
Car.h:@property 會自動完成三件事——生成以下劃線開頭的實例變量、聲明 setter/getter 方法、並實現 setter/getter。
// Car.h
#import <Foundation/Foundation.h>
@interface Car : NSObject {
// NSString *_brand;
// float _price;
}
// 屬性聲明
@property NSString *brand;
@property float price;
// @property 到底做了什麼?
// 1. 自動生成以 _ 開頭的實例變量
// 2. 自動生成 set/get 的聲明
// 3. 自動生成 set/get 的實現
// 自定義初始化方法
- (id)initWithBrand:(NSString *)brand price:(float)price;
- (void)run;
- (void)stop;
@end
Car.m:可以看到,若手寫 setter/getter,效果與 @property 自動生成的一致;同時演示了自定義初始化方法的寫法。
// Car.m
#import "Car.h"
@implementation Car
// 手寫 setter/getter 的效果等同於 @property 自動生成
// - (void)setBrand:(NSString *)brand { _brand = brand; }
// - (NSString *)brand { return _brand; }
// - (void)setPrice:(float)price { _price = price; }
// - (float)price { return _price; }
- (id)initWithBrand:(NSString *)brand price:(float)price {
self = [super init];
if (self) {
_brand = brand;
_price = price;
}
return self;
}
- (void)run {
NSLog(@"車正在疾馳");
}
- (void)stop {
NSLog(@"停車");
}
@end
核心要點:@property 本質上是語法糖,幫我們省去了大量重複的成員變量聲明與存取方法編寫。