创建快捷线程安全的数组 [英] Create thread safe array in swift

查看:179
本文介绍了创建快捷线程安全的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个迅速的线程问题。我有它的一些对象的数组。在一个委托类获取有关每一秒的新对象。从那以后,我要检查的对象是已在阵中,所以我必须要更新的对象,否则我要删除/添加新对象。

I have a threading problem in swift. I have an array with some objects in it. Over a delegate the class gets new objects about every second. After that I have to check if the objects are already in the array, so I have to update the object, otherwise i have to delete / add the new object.

如果我添加一个新的对象,我必须先获取在网络上的一些数据。这通过一个块handelt。

If I add a new object I have to fetch some data over the network first. This is handelt via a block.

现在我的问题是,我如何与共这个任务?

Now my problem is, how to I synchronic this tasks?

我已经尝试了dispatch_semaphore,但是这一次阻止用户界面,直到块结束。

I have tried a dispatch_semaphore, but this one blocks the UI, until the block is finished.

我也尝试了简单的布尔变量,如果当前执行的程序段,并跳过它检查比较方法同时。

I have also tried a simple bool variable, which checks if the block is currently executed and skips the compare method meanwhile.

不过,这两种方法都不太理想。

But both methods are not ideal.

最新最好的方式来管理阵列,我不希望有数组中的重复数据。

Whats the best way to manage the array, I don't wanna have duplicate data in the array.

推荐答案

Kirsteins 是正确的,但你不知道总是需要使用调度队列。您可以使用:

Kirsteins is correct, but you don't always need to use dispatch queue. You can use:

objc_sync_enter(array)
// manipulate the array
objc_sync_exit(array)

这应该做的伎俩。对于额外的奖励,你可以创建一个函数来使用,当您需要线程安全:

This ought to do the trick. For added bonus, you can create a function to use whenever you need thread safety:

func sync(lock: AnyObject, closure: () -> Void) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}

...
var list = Array<String>()
sync (list) {
   list.append("something")
}

这篇关于创建快捷线程安全的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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