唯一作用:為現有類添加方法(無法添加實例變量)。
適用場景:無法修改原類源碼(如系統框架類、第三方庫)需擴展功能時。
// Student.h 原類
@interface Student : NSObject
@property (nonatomic, strong) NSString *name;
@end
// Student+Test.h 類目聲明
@interface Student (Test)
- (void)test;
@end
// Student+Test.m 類目實現
@implementation Student (Test)
- (void)test {
NSLog(@"這裡是Student類目的test方法");
}
@end
關鍵點:
@interface 類名 (類目名)[student test];可視為匿名類目,用於聲明私有方法/屬性,僅類內部可見。
// Student.m 實現文件中
@interface Student ()
- (void)cheat; // 私有方法聲明
@property (nonatomic, assign) BOOL isCheating; // 私有屬性
@end
@implementation Student
// 類目方法實現
- (void)test { NSLog(@"類目方法"); }
// 私有方法實現
- (void)cheat { NSLog(@"正在作弊"); }
@end
工程規範:
定義一組方法聲明清單,不實現。遵守協議的類必須實現規定方法(除可選方法)。
@protocol TestProtocol@required - (void)requiredMethod; // 必須實現(默認) @optional - (void)optionalMethod; // 可選實現 @end
- (void)doSomethingWithDelegate:(id)delegate;
@property (nonatomic, weak) iddelegate;
核心價值:定義行為契約,實現面向接口編程,解耦調用者與實現者。UITableViewDataSource、UITableViewDelegate等均為協議模式。
| 特性 | Category類目 | Extension延展 | Protocol協議 |
|---|---|---|---|
| 目的 | 擴展現有類方法 | 聲明私有接口 | 定義行為契約 |
| 可見性 | 公開 | 私有(僅.m可見) | 公開 |
| 添加ivar | 不可 | 不可 | 不可 |
| 實現位置 | 獨立文件 | .m文件內 | 遵守者類內 |
| 典型用途 | 系統類擴展、功能模塊化 | 私有方法/屬性聲明 | 委托模式、API約束 |