利用 UIControl 內建的 Target-Action 機制,自訂事件類型 (擴展 UIControlEvents),實現類別間鬆耦合通訊。優於 Notification Center 的點對點精準傳遞,優於 Delegate 的多播支援。
// SocketUtils.h #import#import "AsyncSocket.h" @interface SocketUtils : UIControl // 自訂事件常數 (使用保留位 24-27) typedef NS_ENUM(NSUInteger, SocketUtilsEvent) { UIControlEventAlert = 0x00000001 << 25, // 0x02000000 UIControlEventError = 0x00000001 << 26 // 0x04000000 }; @end
// SocketUtils.m
- (void)someAsyncCallback {
// 內部邏輯判斷需通知外部
[self sendActionsForControlEvents:UIControlEventAlert];
}
// Head.h #import#import "SocketUtils.h" @interface Head : UIView @property (nonatomic, strong) SocketUtils *socketUtils; @end
// Head.m
#import "Head.h"
@implementation Head
@synthesize socketUtils = _socketUtils;
- (instancetype)init {
self = [super init];
if (self) {
_socketUtils = [[SocketUtils alloc] init];
// 關鍵:註冊 Target-Action
[_socketUtils addTarget:self
action:@selector(socketEvent:)
forControlEvents:UIControlEventAlert];
}
return self;
}
- (void)socketEvent:(SocketUtils *)sender {
NSLog(@"Event received: %@", sender);
// 處理事件邏輯
}
@end
| 環節 | 關鍵點 |
|---|---|
| 繼承 UIControl | 獲得 addTarget:action:forControlEvents: 等事件機制 |
| 事件常數定義 | 使用 UIControlEventApplicationReserved 保留位 (24-27),避免衝突系統事件 |
| Target 保留策略 | UIControl 對 target 不保留 (weak),需確保 target 生命週期 ≥ control |
| Action 簽名 | 三種合法形式:- (void)action、- (void)action:(id)sender、- (void)action:(id)sender forEvent:(UIEvent*)event |
| 多播支援 | 同一事件可註冊多組 target-action,依序呼叫 |
| 機制 | 耦合度 | 多播 | 型別安全 | 適用場景 |
|---|---|---|---|---|
| Target-Action (本文) | 低 | ✓ | 中 (Selector) | UI 控制元件、非同步回調 |
| Delegate | 中 | ✗ (單播) | 高 (Protocol) | 資料源、單一回調 |
| Notification | 極低 | ✓ | 低 (字串 Key) | 廣播、跨層級通訊 |
| Block Callback | 低 | ✗ (單一) | 高 | 非同步完成、簡單回調 |
UIControl 機制不直接支援自訂參數傳遞,兩種替代方案:
sender.customParam// 錯誤:self 持有 control,control weak 持有 self → 看似無循環
// 但若 self 被其他物件強持有,control 不會釋放 → 事件仍會觸發
// 解決:在 deinit 移除註冊
- (void)dealloc {
[_socketUtils removeTarget:self action:@selector(socketEvent:)
forControlEvents:UIControlEventAlert];
}
基於 UIControl 的自訂事件機制,結合了 Target-Action 的鬆耦合優勢與多播能力,是 iOS 開發中實現元件間通訊的輕量級方案。關鍵在於:正確繼承 UIControl、使用保留位定義事件、妥善處理 Target 生命週期。對於需要傳遞豐富參數的場景,建議搭配 Block 回調或擴充 Sender 物件屬性使用。