IOS在另一个线程中解析JSON数据?

我目前正在研究一个应用程序,它在位置发生变化时解析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还有很多,所以请查看文档以获取更多信息.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...