Objective C - 块问题?

发布于 2024-11-01 06:48:51 字数 251 浏览 0 评论 0原文

我有以下方法

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

如何使块同步完成其工作,以便在检索结果之前不会返回结果?

I have the following method

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

How can i make the block to do it's job synchronously, so that it doesn't return the result before it was retreived?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不必了 2024-11-08 06:48:51

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

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

Grand Central Dispatch 参考

You are calling dispatch_async which dispatches your block asynchronously. Try using dispatch_sync or dispatch_main if your goal is to block the main thread.

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

Grand Central Dispatch Reference

漫漫岁月 2024-11-08 06:48:51

使用dispatch_sync而不是dispatch_async - 那么当前线程将被阻塞,直到该块在主线程上完成执行。

Use dispatch_sync instead of dispatch_async - then the current thread will be blocked until the block has finished executing on the main thread.

你如我软肋 2024-11-08 06:48:51

既然您似乎想在不同的线程上执行一个方法并获取返回值,为什么不使用 NSInitation 呢?

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

Since it seems like you want to perform a method on a different thread and get a return value, why don't you use an 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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文