ios - 在调度 block 中分配的变量返回 null

标签 ios iphone objective-c multithreading grand-central-dispatch

我正在尝试在后台线程中运行网络调用,这样它就不会在等待时卡住我的应用程序。

当我这样做时会发生调用:

nextTime = [myObj getNextTime];

我一拿到它就做一个 NSLog,而且那个工作。
但是,当我在调度 block 之外时,同样
NSLog 打印出 null。
myObj *current = ((myObj *)sortedArray[i]);
__block NSString *nextTime;
dispatch_queue_t queue =     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
    nextTime = [myObj getNextTime];
    NSLog(@"inside%@",nextTime);
    dispatch_sync(dispatch_get_main_queue(), ^{

    });
});


NSLog(@"outside%@",nextTime);

任何想法为什么外部日志打印空?我做错了什么,我只是错过了吗?谢谢!

最佳答案

那是因为您将它设置在异步 block 中,并且异步 block 立即返回。如果您查看两个日志的时间戳,您会发现外部日志实际上是在内部日志和变量设置之前发布的。

来自 GCD docsdispatch_async() :

This function is the fundamental mechanism for submitting blocks to a dispatch queue. Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked. The target queue determines whether the block is invoked serially or concurrently with respect to other blocks submitted to that same queue. Independent serial queues are processed concurrently with respect to each other.

关于ios - 在调度 block 中分配的变量返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21763364/

相关文章:

iphone - iOS 创建宏

ios - 'NSInvalidArgumentException',原因 : 'Unable to parse constraint format

ios - OAuthSwift (1) 连接

iOS Swift 以编程方式在 Firebase 实时数据库中创建子级

c# - 无法从 xamarin 中的 TableView RowSelected 加载 ViewController

iphone - 显示录音的声波

iphone - iPhone/iPod 模拟器和设备之间的差异

objective-c - Objective C @autoreleasepool 指令

objective-c - 使用什么格式来录制音频?

ios - 警告 : NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)