在 iOS 開發中,常會遇到需要替既有類別補上一些屬性或方法的情況。一般做法是繼承並覆寫,但如果只是加幾個簡單的東西,另開一個子類顯得笨重。這時候 Category(類別)是更輕量的選擇。
宣告時只需在 interface 後加上括號與類別名稱:
@interface UIImageView (CategoryName)
替 UIImageView 加一個 speak 方法:
@interface UIImageView (image) - (void)speak:(NSString *)words; @end
接著實作:
@implementation UIImageView (image)
- (void)speak:(NSString *)words {
NSLog(@"%@", words);
}
@end
完成後,任何 UIImageView 都能直接呼叫 speak 方法。
類別本身無法存放實例變數,因此添加屬性時需要搭配 Objective-C Runtime 的關聯機制。先宣告屬性:
@interface UIImageView (title) @property (nonatomic, strong) NSString *title; @end
然後匯入 runtime 標頭並實作 getter 與 setter:
#import <objc/runtime.h>
@implementation UIImageView (title)
static void * MyKey = (void *)@"MyKey";
- (NSString *)title {
return objc_getAssociatedObject(self, MyKey);
}
- (void)setTitle:(NSString *)title {
objc_setAssociatedObject(self, MyKey, title, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
關聯策略可視需求選用:副本用 OBJC_ASSOCIATION_COPY_NONATOMIC,強引用用 OBJC_ASSOCIATION_RETAIN_NONATOMIC,弱引用則是 OBJC_ASSOCIATION_ASSIGN(不持有)。
主要有兩點:
關聯物件是在執行期動態為物件掛上屬性,實務上使用頻率不高,但遇到 Category 無法加 ivar 的限制時它就是標準解法,值得熟悉。