Accessing Instance Attributes from Secondary Thread (iPhone-SDK)
I have a class with an NSDictionary attribute. Inside this class I dispatch another thread to handle NSXMLParser handling. Inside my -didStartElement, I access the dictionary in the class (to compare an element found in the XML to one in the dictionary).
At this point I get undefined results. Using NSLog (I'm not advanced in XCode debugging), I see that it bombs around access of the NSDictionary. I tried just iterating the dictionary and dumping the key/values inside the didStartElement and this bom开发者_StackOverflowbs at different keys each time.
The only thing I can conclude is that something is not kosher that I'm doing with regards to accessing main thread attributes from the secondary thread. I'm somewhat new to multithreading and am not sure what the best protocol is safely access attributes from additional threads.
Thanks all.
I would be surprised if you could access memory used by one thread in another thread unless that dictionary is static/global. I would take one of two approaches, not knowing the intricacies of the iPhone SDK -
- Handle all of the dictionary access in the separate thread (population, instantiation, lookups, etc.)
- Use some sort of iPhone equivalent of a thread-safe dictionary: link
There are few ways to enable thread-safe access to instances variables in Objective-C. The simplest way is to define your @property declaration as atomic. In this case the auto-generated setters and getters would be synchronized on self.
The other way is to wrap your critical code in a @synchronized block.
The most preferable way would be to create an NSOperation subclass that handles the fetching and parsing, and provides callbacks via delegation or blocks (if you're >= iOS4.0), to notify your consumer that the operation was completed.
Concurrent NSOperations require a bit of boilerplate code in order to get them working correctly, see this (the example is for Snow Leopard, but the concept is the same): http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
精彩评论