views:

209

answers:

1

I have an iPhone app with a secondary thread to handle XML parsing. Inside some of those methods, I need to reference dictionaries (for look up, not modification) created and populated in the main thread.

Apple's documentation indicated to me that global variables might be the best way to accomplish this. I'm just now sure what the implementation would look like. Define the dictionaries at the top of .m and access them normally inside the secondary thread?

+1  A: 

NSDictionary is thread-safe, so it's probably not a threading issue unless your initializer allocates the global as an NSMutableDictionary (not thread-safe) and then the secondary thread tries to access it while it's still being populated.

(If this is the case, your initializer should first allocate the NSMutableDictionary into a local variable, populate it, then copy the finished local to the global using NSDictionary's +dictionaryWithDictionary: or -initWithDictionary:.)

Alternatively, could it be that you're not retaining the global when initializing it?

tedge
Wow. Do I feel stupid. Adding a retain call fixed it. I was using the [NSDictionary dictionaryWithContentsofFile] to load a plist.So since my init method populated the dictionary and then exited, a race began between how quickly the dictionary was deallocated and how quickly my secondary thread went to dump the contents to NSLog?I thought dictionaryWithContentsofFile would return a retained reference. I thought I would only need retain following an explicit alloc/init. So what is the best rule of thumb on when to retain or not?
Travis
Actually, it's the other way around: alloc implicitly retains, and just about every other method (except for "new" or "copy") returns an autoreleased object, so if you want it to stick around after your method returns you need to explicitly retain it.For more info:http://developer.apple.com/Mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html
tedge