iPhone上的多线程和JSON/NSURLConnection [英] Multithreading and JSON/NSURLConnection on the iPhone
问题描述
我正在编写一个使用多线程和缓存的应用程序.与Apple的 TopSongs 示例代码非常相似.启动时,我需要在JSON feed中获取对象的值.
I am writing an app that uses multithreading and cache. Quite similar to Apple's TopSongs sample code. Upon startup, I need to grab the value of an object in a JSON feed.
现在我担心这样做会破坏应用程序的工作流程,并且如果我使用NSURLConnection会阻塞线程或其他操作.我可以不使用NSURLConnection的委托方法直接下载JSON提要(它只有一个对象)吗?如果我在委托文件中实现委托方法,则应用程序将完成applicationDidFinishLaunching:application
方法,然后转到
Now I am afraid doing so would ruin the workflow of the app, and block a thread or something if I use NSURLConnection. Can I just download that JSON feed (it only has one object) without using NSURLConnection's delegate methods? If I implement the delegate methods in my delegate file, then the app will finish up applicationDidFinishLaunching:application
method and THEN go to
connection:didReceiveResponse:
connection:didReceiveData:
connection:didFailWithError:
connectionDidFinishLoading:
如何避免这种情况?我需要在applicationDidFinishLaunching:application
的开头获取时间戳(存储在该JSON文件中),因为该方法的其余部分取决于该时间戳.
How can I avoid that? I need to get the timestamp (stored in that JSON file) right at the beginning of applicationDidFinishLaunching:application
as the rest of that method depend on that timestamp.
谢谢
推荐答案
有两种方法可以实现此目的:
There are two ways to achieve this:
使用NSURLConnection的 sendSynchronousRequest ,但这会阻塞直到收到响应为止
Use the sendSynchronousRequest of NSURLConnection, but this will block until a response is received
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
或(首选选项)
将依赖JSON的代码移动到单独的方法.照常使用NSURLConnection的异步+委托方法,但是在您的 applicationDidFinishLaunching 方法中,显示某种HUD 通知用户发生了什么情况,然后在 connection:didReceiveResponse 方法或 connectionDidFinishLoading 方法中调用依赖于JSON(并且现在将具有JSON )并关闭HUD.
Move the code which relies on the JSON to a seperate method. Use the asynchronous + delegate methods of NSURLConnection as normal, but in your applicationDidFinishLaunching method display some sort of HUD to inform the user of what's happening and then in the connection:didReceiveResponse method or connectionDidFinishLoading method call your new method which relies on the JSON (and will now have the JSON) and dismiss the HUD.
这篇关于iPhone上的多线程和JSON/NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!