分派块中分配的变量返回空 [英] Variable assigned in dispatch block coming back null

查看:71
本文介绍了分派块中分配的变量返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在后台线程中运行网络调用,以使其在等待时不会冻结我的应用程序.

I'm trying to make a network call run in a background thread so it doesn't freeze my app while it's waiting.

当我这样做时会打电话:

The call happens when I do:

nextTime = [myObj getNextTime];

我一收到NSLog,就可以正常工作. 但是,当我不在调度块之外时, NSLog打印出空值.

I do an NSLog as soon as I get it, and that one works. However, when I'm outside of the dispatch block, the same NSLog prints out 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);

有什么想法为什么外部日志打印为空?我是在做些可怕的错误,而我只是错过了吗?谢谢!

Any ideas why the outer log is printing null? Am I doing something horribly wrong and I just missed it? Thanks!

推荐答案

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

That's because you're setting it inside an asynchronous block, and asynchronous blocks return immediately. If you look at the time stamps of the two logs, you'll see that the outer log is actually being posted before both the inner log, and the setting of the variable.

来自dispatch_async()上的"nofollow> GCD文档:

From the GCD docs on dispatch_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.

这篇关于分派块中分配的变量返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆