但某些时候,我们希望让主线程等待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];
[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]; //挂起主线程
}
新闻热点
疑难解答