从辅助线程访问实例属性 (iPhone-SDK)
我有一个带有 NSDictionary 属性的类。在这个类中,我调度另一个线程来处理 NSXMLParser 处理。在我的 -didStartElement 中,我访问类中的字典(将 XML 中找到的元素与字典中的元素进行比较)。
此时我得到未定义的结果。使用 NSLog (我在 XCode 调试方面并不先进),我发现它在 NSDictionary 的访问周围发生了爆炸。我尝试迭代字典并将键/值转储到 didStartElement 中,并且每次都会在不同的键上爆炸。
我唯一可以得出的结论是,我在从辅助线程访问主线程属性方面所做的事情并不合理。我对多线程有点陌生,不确定最好的协议是从附加线程安全访问属性。
谢谢大家。
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 bombs 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以访问另一个线程中一个线程使用的内存,除非该字典是静态/全局的,我会感到惊讶。我会采取两种方法之一,不知道 iPhone SDK 的复杂性 -
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 -
在 Objective-C 中,有几种方法可以实现对实例变量的线程安全访问。最简单的方法是将 @property 声明定义为原子声明。在这种情况下,自动生成的 setter 和 getter 将自行同步。
另一种方法是将关键代码包装在 @synchronized 块中。
最可取的方法是创建一个 NSOperation 子类来处理获取和解析,并通过委托或块提供回调(如果您 >= iOS4.0),以通知您的消费者操作已完成。
并发 NSOperations 需要一些样板代码才能使其正常工作,请参阅此(示例适用于 Snow Leopard,但概念是相同的): http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
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/