萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 主線程阻塞技巧:使用 NSInvocation 實現同步等待 IO 操作

場景痛點

主線程建立資料夾後,需等待完成才能在其中建立檔案。performSelectorOnMainThread:withObject:waitUntilDone: 僅支援單一參數,無法滿足多參數方法(如 createDirectoryAtPath:withIntermediateDirectories:attributes:error:)的同步呼叫需求。

解決方案:NSInvocation 封裝多參數呼叫

- (void)createRecordDirectoryBlockingMainThread {
    NSFileManager *dfm = [NSFileManager defaultManager];
    SEL sel = @selector(createDirectoryAtPath:withIntermediateDirectories:attributes:error:);
    
    // 1. 取得方法簽名(含參數型別資訊)
    NSMethodSignature *sig = [dfm methodSignatureForSelector:sel];
    
    // 2. 建立 Invocation 物件
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
    [inv setTarget:dfm];
    [inv setSelector:sel];
    
    // 3. 依序設定參數(索引 0、1 保留給 self、_cmd,實際參數從 2 開始)
    FilePathManager *fpm = [FilePathManager sharedInstance];
    NSString *path = fpm.programRecordDirectoryPath;
    [inv setArgument:&path atIndex:2];
    [inv setArgument:(void *)&BOOL_NO atIndex:3];
    [inv setArgument:(void *)&ID_NIL atIndex:4];
    [inv setArgument:(void *)&VOID_NULL atIndex:5];
    
    // 4. 在主線程同步執行 invoke,阻塞至完成
    [inv performSelectorOnMainThread:@selector(invoke)
                          withObject:nil
                       waitUntilDone:YES];
}

關鍵點解析

步驟API作用
1methodSignatureForSelector:獲取方法型別編碼,供運行期正確壓棧
2invocationWithMethodSignature:建立可攜帶完整參數的呼叫封裝
3setArgument:atIndex:按參數位置填入值,索引從 2 起算
4performSelectorOnMainThread:... waitUntilDone:YES主線程同步執行 invoke,阻塞呼叫端

常見陷阱

  • 參數索引錯誤: 0=self, 1=_cmd, 2=第一個實際參數
  • 標量類型傳址: BOOL、NSInteger 等需用 (void *)&value 傳遞位址
  • 死鎖風險: 若主線程正在等待背景線程,而背景線程又需主線程資源,將導致死鎖
  • 僅限同步需求: 多數情況應改用 GCD/NSOperation 非同步模式,避免阻塞 UI

結語

NSInvocation 是 Objective-C 運行期呼叫機制的核心,配合 performSelectorOnMainThread:waitUntilDone: 可實現任意簽名方法的主線程同步執行。但請謹慎使用:阻塞主線程會凍結 UI,僅適合極短暫、不可避免的同步場景。

copyright © 萬盛學電腦網 all rights reserved