首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言入門

Objective-C 自訂事件實作:基於 UIControl 事件機制的跨類別通訊

     編輯:C 語言入門

核心思路

利用 UIControl 內建的 Target-Action 機制,自訂事件類型 (擴展 UIControlEvents),實現類別間鬆耦合通訊。優於 Notification Center 的點對點精準傳遞,優於 Delegate 的多播支援。

實作步驟

1. 事件來源類別:繼承 UIControl

// 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

2. 觸發事件

// SocketUtils.m
- (void)someAsyncCallback {
    // 內部邏輯判斷需通知外部
    [self sendActionsForControlEvents:UIControlEventAlert];
}

3. 事件監聽類別

// 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 機制不直接支援自訂參數傳遞,兩種替代方案:

  1. 擴充 UIControl 子類別:新增屬性儲存參數,Action 內讀取 sender.customParam
  2. 改用 Block 回調:參見 OC教程6 代碼塊回調模式

記憶體管理陷阱

// 錯誤: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 物件屬性使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved