I have a class that contains an NSDictionary and periodically, I have a thread writing data into this NSDictionary. Then at other times, I have another view controller reading data out of the class’s NSDictionary.
What’s the best objective-c way to make the data in this class thread-safe so that if you were to ask data for ‘read’, you’re getting the correct version aka, the last written version and not the one that maybe getting written to currently?
As Carl mentioned,
@synchronizedis one option.If you are targeting iOS 4.0+, another one is using a Grand Central Dispatch queue to regulate access to a shared data structure from multiple threads/queues. The WWDC 2010 Session 211 video has a good explanation of this technique.
In a nutshell: you create a custom GCD queue (
dispatch_queue_create()) whose single responsibility is to regulate access to the shared data structure. All code that accesses the shared structure then must do so from inside this queue. Because queues only execute one block of code at a time, no two threads can access the data structure at the same time.