使用GCD时,锁定对象的NSMutableArray,但不锁定对象的其余部分 [英] Lock a NSMutableArray of an object but not the rest of my object when using GCD

查看:24
本文介绍了使用GCD时,锁定对象的NSMutableArray,但不锁定对象的其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有各种属性的User类:

I have a User class which has various properties:

@property (strong, nonatomic) NSString *CandID;
@property (assign, nonatomic) BOOL IsCandidate;
@property (assign, nonatomic) NSInteger ResponseCode;
@property (strong, nonatomic) NSMutableArray *locations;

我的一个ViewController可能具有用户属性,即

One of my ViewControllers may have a user property i.e.

@property (strong, nonatomic) User *user;

此用户可能会被传递到以模态方式启动的后续ViewController.

And this user may be passed to subsequent ViewControllers which are launched modally.

首次初始化用户对象时,我将在大型中央调度中发送一些方法,该方法将通过REST填充locations数组.这个想法是,当有人使用我的应用程序进入屏幕选择位置时,该列表将已经下载.

When the user object is first initialized I am going to send some method off in grand central dispatch that will fill the locations array via REST. The idea is that by the time someone using my app gets to the screen to pick a location, the list will already be downloaded.

我想做的是在gcd使用它时锁定位置区域,我曾经使用过类似的方法

What I want to do is lock the locations area when the gcd is using it, I have used something like

[someLock lock] ... [someLock unlock]

过去,但是我想要的是被锁定的locations数组,但是可以从主线程访问其余用户对象的方法和属性.实现此目标的最佳方法是什么?

in the past but what I want is the locations array to be locked but the rest of the user object's methods and properties to be accessible from the main thread. What is the best way to achieve this?

推荐答案

我会将后台线程中的位置提取到单独数组中,并且仅分配数据完成后将其发送给用户,例如:

I would fetch the locations in a background thread into a separate array, and only assign it to the user when the data is complete, something like:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSMutableArray *locations;
    // ... fill locations ...        
    dispatch_sync(dispatch_get_main_queue(), ^{
        user.locations = locations;
        // ... perhaps refresh some view or send a notification ...
    })
});

然后 user.locations 始终可以在主线程上访问,并且为 nil 或包含已获取的位置.

Then user.locations is always accessible on the main thread, and is either nil or contains the fetched locations.

这篇关于使用GCD时,锁定对象的NSMutableArray,但不锁定对象的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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