| 特性 | 關鍵字 | 核心用途 | 可見性 |
|---|---|---|---|
| 類別 | @interface Class (Name) | 為現有類別新增方法 (無法新增實例變數) | 公開 |
| 延展 | @interface Class () | 宣告私有方法/屬性/實例變數 (匿名類別) | 私有 (.m 內) |
| 協定 | @protocol Name | 定義方法契約,供類別遵循實作、委託/代理使用 | 公開 |
// NSString+Validation.h
@interface NSString (Validation)
- (BOOL)isValidEmail;
- (BOOL)isValidPhoneNumber;
@end
// NSString+Validation.m
@implementation NSString (Validation)
- (BOOL)isValidEmail {
NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [pred evaluateWithObject:self];
}
- (BOOL)isValidPhoneNumber {
// 實作...
return YES;
}
@end
// 使用
NSString *email = @"test@example.com";
if ([email isValidEmail]) { /* ... */ }
ClassName+CategoryName.h/mClassName (CategoryName)Foundation (基礎擴充)、UI (介面相關)、Internal (內部私有)@interface ClassName ().m 檔案頂部 (編譯後不會外露)@implementation 區塊// Student.h (公開介面)
@interface Student : NSObject
@property (nonatomic, strong) NSString *name;
- (void)study;
@end
// Student.m (私有實作細節)
@interface Student ()
- (void)cheat; // 私有方法宣告
@property (nonatomic, assign) NSUInteger cheatCount; // 私有屬性
@end
@implementation Student
- (void)study { NSLog(@"正經讀書"); }
- (void)cheat {
_cheatCount++;
NSLog(@"偷偷作弊 %lu 次", _cheatCount);
}
@end
@protocol NetworkDelegate// 必須實作 @required - (void)requestDidFinish:(NSData *)data; - (void)requestDidFail:(NSError *)error; // 可選實作 @optional - (void)requestDidProgress:(float)progress; - (BOOL)shouldCacheResponse:(NSURLResponse *)response; @end
// 介面宣告 @interface NetworkManager : NSObject @property (nonatomic, weak) iddelegate; @end // 實作者 @interface MyController : UIViewController @end @implementation MyController - (void)requestDidFinish:(NSData *)data { /* 必須實作 */ } - (void)requestDidProgress:(float)progress { /* 可選實作 */ } // 未實作 requestDidFail → 編譯警告 @end
// 方法參數限制 - (void)processData:(id)processor; // 屬性限制 @property (nonatomic, strong) id dataModel;
// 1. 協定定義契約 @protocol HTTPClientDelegate- (void)client:(id)client didReceiveResponse:(id)response; - (void)client:(id)client didFailWithError:(NSError *)error; @end // 2. 延展隱藏內部狀態 @interface HTTPClient () @property (strong) NSURLSession *session; @property (strong) NSMutableDictionary *pendingRequests; - (void)handleResponse:(NSURLResponse *)response forRequestID:(NSString *)id; @end // 3. 類別擴充便利方法 @interface HTTPClient (Convenience) - (void)GET:(NSString *)url parameters:(NSDictionary *)params completion:(void(^)(id, NSError*))block; - (void)POST:(NSString *)url body:(id)body completion:(void(^)(id, NSError*))block; @end
.h 主介面.m 延展Class+FeatureNSObject、善用 @optionalid 表達多重契約類別、延展、協定構成 Objective-C 模組化與封裝的鐵三角。類別解決「無法修改源碼時擴充功能」,延展解決「實作細節隱藏」,協定解決「跨類別契約定義」。三者配合使用,能打造出介面清晰、實作隱藏、擴充彈性的專業級程式碼架構。