目标C - 阻止问题?

时间:2011-04-13 18:23:11

标签: objective-c grand-central-dispatch objective-c-blocks

我有以下方法

+ (NSString*)getMeMyString
{
   NSString *result;
   dispatch_async(dispatch_get_main_queue(), ^{
        result = [ClassNotThreadSafe getString];
    });
   return result;
}

如何让块同步完成它的工作,以便它在返回之前不会返回结果?

3 个答案:

答案 0 :(得分:5)

您正在调用dispatch_async,它会异步调度您的块。如果你的目标是阻止主线程,请尝试使用dispatch_syncdispatch_main

+ (NSString*)getMeMyString
{
   __block NSString *result;
   dispatch_sync(dispatch_get_main_queue(), ^{
        result = [ClassNotThreadSafe getString];
    });
   return result;
}

Grand Central Dispatch参考

答案 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];