如何在 iPhone 应用程序中从主线程启动新线程
我有一个用于移动购物的应用程序。我有一个“LocationModel”单例对象,它从 pList 获取地址列表并将每个地址转换为“Location”对象。在位置对象中,我有一个“纬度”和“经度”变量。目前,我有一个方法,它迭代位置对象数组,并使用每个位置对象内的地址 ping google.api 服务器,然后使用 NSXML 解析器解析返回数据类型,提取坐标并将其分配给每个位置对象。
现在所有这些都是在主线程上完成的,因此当应用程序启动几秒钟时 GUI 就会被锁定。我想在应用程序委托的主要方法中启动一个新线程,该线程执行在后台获取坐标的工作。但我以前从未做过多线程,我查看了Apple并发编程指南和线程指南,它似乎令人不知所措。有人可以向我指出一些易于理解和/或有示例代码的资源吗?
非常感谢
I have an App that is used for mobile shopping. I have a "LocationModel" singleton object that gets a list of addresses from a pList and converts each address into a "Location" object. In the location object I have a "Latitude" and "longitude" variable. Currently I have a method that iterates through the location object array and pings the google.api servers with the address inside each location object, the return datatype is then parsed using NSXML parser and the coordinates extracted and assigned to each location object.
Right now all this is done on the main thread and as such the GUI is locked when the app starts for a good couple of seconds. I would like to start a new thread in the appdelegate's main method that does this work of getting coordinates in the background. But I have never done multi threading before and I looked at the Apple concurrent programming guides and Threading guide and it seems overwhelming. Can someone please point me to some resources that are easy to understand and or have sample code.
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以查看 此方法。这在每个 NSObject 子类上都可用。这将在后台生成一个新线程并运行该方法。您可以将所有与下载和处理相关的代码放在该方法中。要记住的重要一点是,您无法从主线程以外的任何线程更新 UI。因此,一旦准备好更新 UI,您应该使用performSelectorOnMainThread:withObject:waitUntilDone: 来调用更新 UI 的方法。
虽然这应该足以开始,但我建议您查看 GCD。
You can look at this method. This is available on every
NSObject
subclass. This will spawn a new thread on the background and run that method. You can put all the code related to downloading and processing in the method. An important point to remember is that you can't update UI from any thread other than the main thread. So once you're ready to update the UI, you should useperformSelectorOnMainThread:withObject:waitUntilDone:
to call a method which will update the UI.While this should suffice to start with, I recommend that you look at GCD.