gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:40:23 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com