但某些時候,我們希望讓主線程等待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]; //掛起主線程
}