PaolaJ.
PaolaJ.

Reputation: 11532

How to make dictionary NSDictionary be thread safe for reading, inserting?

At every start of application I have to fetch couple .plists from server and later some of them I am using in code ( depends on user's choice ). To avoid loading for very .plist I am at the entering in app I download all and parse every into dictionary and all of them put in cache dictionary ( key is plist name and value is plist parsed into dictionary). How to make dictionary ( NSDictionary or to use something else ) be thread safe for reading, inserting ?

Upvotes: 2

Views: 2189

Answers (1)

driis
driis

Reputation: 164291

You can used @synchronized around each access to the shared object. I'd recommend building a wrapper object used for access so that you don't accidentally forget to synchronize in one place in the code.

@synchronized {
    NSString* settingValue = self.sharedDictionary[@"key"];
}

This is a language feature that gets translated to an exclusive mutex. If you need more control over how you sync, you should use one of the other synchronization primitives provided. Apple has a nice overview on that in their Threading Programming Guide.

Upvotes: 1

Related Questions