但某些時候,我們希望讓主線程等待IO操作完成——例如主線程建立了一個檔案夾後,等待完成,再往檔案夾中建立檔案。
NSObject類有一個方法performSelectorOnMainThread:withObject:waitUntilDone可以讓主線程掛起,但selector至多隻能帶一個可傳參數,這時需要用到NSInvocation類來解決這個問題。
代碼如下:
- (void)createRecordDirectoryBlockingMainThread
{
NSFileManager *dfm = [NSFileManager defaultManager];
SEL sel = @selector(createDirectoryAtPath:
withIntermediateDirectories:
attributes:
error:);
NSMethodSignature *sig = [dfm methodSignatureForSelector:sel];
//方法的簽名,實際上包含了目標,選取器,及各參數的類型資訊,但並不含有目標和方法的記憶體位址。這些資訊是為了在函數壓棧時準確得到各參數的值
NSInvocation *ivct = [NSInvocation invocationWithMethodSignature:sig];
[ivct setTarget:dfm];
[ivct setSelector:sel]; //提供方法的記憶體位址
FilePathManager *fpm = [FilePathManager sharedInstance];
NSString *path = fpm.programRecordDirectoryPath;
[ivct setArgument:&path atIndex:2]; //參數在數組中的索引從2開始
[ivct setArgument:(void *)&BOOL_NO atIndex:3]; //(void *)的類型轉換可以避免編譯器警告
[ivct setArgument:(void *)&ID_NIL atIndex:4];
[ivct setArgument:(void *)&VOID_NULL atIndex:5];
[ivct performSelectorOnMainThread:@selector(invoke)
withObject:nil
waitUntilDone:YES]; //掛起主線程
}