目标C-阻止问题?

| 我有以下方法
+ (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];
    

要回复问题请先登录注册