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.