Create thread safe array in Swift

patrickS picture patrickS · Jan 28, 2015 · Viewed 52.8k times · Source

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.

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?

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.

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

Answer

skim picture skim · Mar 11, 2015

Update for Swift

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