iOS-Grand Central Dispatch从dispatch_async中的块获取价值 [英] iOS - Grand Central Dispatch getting value from block in dispatch_async

查看:60
本文介绍了iOS-Grand Central Dispatch从dispatch_async中的块获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码从网上下载一些数据.我需要像以前一样保留数据吗?同样,来自该块内部的NSLog语句显示该数组已被填充,但是当我在该块外部运行NSLog时,该数组显示为(null).我如何将数据保存在dispatch_async方法之外?

I'm using below code to download some data from the web. Am I right that I need to retain the data like I have done? Also the NSLog statement from inside the block shows that the array has been populated, but when I run the NSLog outside the block the arrays show as (null). How would I save the data outside dispatch_async method?

    __block NSArray *downloadedCareerIds;
    __block NSArray *diskCareerIds;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        /* Download stuff */

        downloadedCareerIds = [[CareersParser idsFrom:@"web"] retain];
        diskCareerIds = [[CareersParser idsFrom:@"disk"] retain];

        DLog(@"downloadedCareerIds: %@", downloadedCareerIds);

        DLog(@"diskCareerIds: %@", diskCareerIds);

    });


    DLog(@"downloadedCareerIds: %@", downloadedCareerIds);

    DLog(@"diskCareerIds: %@", diskCareerIds);

推荐答案

dispatch_async是一种非阻塞方法,因此将立即返回.因此,当调用该块外部的DLog语句时,大多数情况下将不会设置它们.因此,您看不到从内部日志语句中获得的值.

dispatch_async is a non blocking method so it will return immediately. So when the DLog statements outside the block are called, they will mostly not have been set. Hence you don't see the values you get from the internal log statements.

如果要对同一方法中的数据进行操作,则必须发送无意义的阻塞dispatch_sync或可以在该块中调用这些方法.

If you want to act on the data within the same method, you will have to either send a blocking dispatch_sync which is pointless or you can call the methods within the block.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    ....

    [self doStuffWithTheArrays];
});

一旦执行了该块,这些对象将是可用的,前提是它们是实例变量,否则您将丢失引用.

Once the block is executed the objects will be available provided they are instance variables or you will lose the references.

这篇关于iOS-Grand Central Dispatch从dispatch_async中的块获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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