我有以下方法
+ (NSString*)getMeMyString
{
NSString *result;
dispatch_async(dispatch_get_main_queue(), ^{
result = [ClassNotThreadSafe getString];
});
return result;
}
如何让块同步完成它的工作,以便它在返回之前不会返回结果?
答案 0 :(得分:5)
您正在调用dispatch_async
,它会异步调度您的块。如果你的目标是阻止主线程,请尝试使用dispatch_sync
或dispatch_main
。
+ (NSString*)getMeMyString
{
__block NSString *result;
dispatch_sync(dispatch_get_main_queue(), ^{
result = [ClassNotThreadSafe getString];
});
return result;
}
答案 1 :(得分:4)
使用dispatch_sync
代替dispatch_async
- 然后阻止当前线程,直到块在主线程上完成执行。
答案 2 :(得分:2)
由于您似乎想在不同的线程上执行方法并获得返回值,为什么不使用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];