常會看到在 .h 和 .m 檔裡都有 @interface 的敘述,一開始覺得很納悶,@interface
不是只要寫在 .h 就好了嗎?不過仔細看又略有不同,在 .m 的 @interface 敘述後面還多了
小括號 ()。
// Classname.m
@interface Classname() {
id _instanceVar;
}
@property NSObject *extraProperty;
@end
原來這種用法叫做
類別延伸 (class extenstion)。好處在於可以定義額外的 property, 實體
變數(需要定義在大括號裡)和方法來擴充類別,而在這個匿名的 category 所以定義的方法,
必須在這個類別的 implementation 區段實作。這些 private 的方法和 property 讓類別延伸也符合了 OO 中封裝 (Encapsulation) 的精神,不需要將實作的資料和內容被看見。
另外一個常見的 property 用法便是對外宣告為 readonly 對內為 readwrite:
// XYZPerson.h
@interface XYZPerson : NSObject
...
@property (readonly) NSString *uniqueIdentifier;
- (void)assignUniqueIdentifier;
@end
// XYZPerson.m
@interface XYZPerson ()
@property (readwrite) NSString *uniqueIdentifier; // readwrite 是 default 的屬性所以也可省略不寫
@end
@implementation XYZPerson
...
@end