我有以下方法
+ (NSString*)getMeMyString
{
NSString *result;
dispatch_async(dispatch_get_main_queue(), ^{
result = [ClassNotThreadSafe getString];
});
return result;
}
我怎么能使块做它的工作同步,使它不返回结果之前,它被检索?
您正在调用dispatch_async
,它异步调度您的块。如果您的目标是阻塞主线程,请尝试使用dispatch_sync
或dispatch_main
。
+ (NSString*)getMeMyString
{
__block NSString *result;
dispatch_sync(dispatch_get_main_queue(), ^{
result = [ClassNotThreadSafe getString];
});
return result;
}
中央调度参考
使用dispatch_sync
而不是dispatch_async
-那么当前线程将被阻塞,直到阻塞在主线程上完成执行。
既然你想在不同的线程上执行方法并获得返回值,为什么不使用NSInvocation呢?
SEL theSelector;
NSMethodSignature *aSignature;
NSInvocation *anInvocation;
theSelector = @selector(getString);
aSignature = [ClassNotThreadSafe instanceMethodSignatureForSelector:theSelector];
anInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
[anInvocation setSelector:theSelector];
NSString *result;
[anInvocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES];
[anInvocation getReturnValue:result];