我目前正在研究一个应用程序,它在位置发生变化时解析APPdelegate类中的一些
JSON数据.
我的问题是:“最合适的方式是怎么做的?”目前,在解析数据时,应用程序被“冻结”,直到数据被加载为止.
我需要一些建议:)
谢谢
解决方法
当然有几种方式,包括NSThread,NSOperation和老式的libpthread.但我发现最方便的(特别是对于简单的后台任务)是libdispatch,也称为
Grand Central Dispatch.
使用调度队列,您可以快速将耗时的任务委派给单独的线程(或者更准确地说,执行队列–GCD决定它是线程还是异步任务).这是最简单的例子:
// create a dispatch queue,first argument is a C string (note no "@"),second is always NULL dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue",NULL); // execute a task on that queue asynchronously dispatch_async(jsonParsingQueue,^{ [self doSomeJSONReadingAndParsing]; // once this is done,if you need to you can call // some code on a main thread (delegates,notifications,UI updates...) dispatch_async(dispatch_get_main_queue(),^{ [self.viewController updateWithNewData]; }); }); // release the dispatch queue dispatch_release(jsonParsingQueue);
上面的代码将在单独的执行队列中读取JSON数据,而不是阻塞UI线程.这只是一个简单的例子,GCD还有很多,所以请查看文档以获取更多信息.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。