在 Swift 中创建线程安全数组
我在 Swift 中遇到线程问题.我有一个数组,里面有一些对象.通过委托,该类每秒都会获取新对象.之后我必须检查对象是否已经在数组中,所以我必须更新对象,否则我必须删除/添加新对象.
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,但是这个阻塞了 UI,直到阻塞完成.
I have tried a dispatch_semaphore, but this one blocks the UI, until the block is finished.
我还尝试了一个简单的 bool 变量,它检查当前是否正在执行块并同时跳过比较方法.
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.
管理数组的最佳方式是什么,我不想数组中有重复的数据.
What's the best way to manage the array, I don't wanna have duplicate data in the array.
Swift 更新
推荐的线程安全访问模式是使用 dispatch barrier
:
The recommended pattern for thread-safe access is using dispatch barrier
:
let queue = DispatchQueue(label: "thread-safe-obj", attributes: .concurrent)
// write
queue.async(flags: .barrier) {
// perform writes on data
}
// read
var value: ValueType!
queue.sync {
// perform read and assign value
}
return value