我可以使用后台线程来解析数据吗? [英] Can I use a background thread to parse data?

查看:78
本文介绍了我可以使用后台线程来解析数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用chcsvparser来解析我的应用启动时来自csv文件的数据。在主线程上启动它需要太长时间,所以我想在后台线程上执行此操作。但我读到你不能在线程之间传递对象。解析器输出一个NSArray,有没有办法做到这一点?我还读过你不应该从后台线程更改UI,但是这个数组会加载一个表视图。

I'm using chcsvparser to parse data from a csv file on my apps launch. It's taking way too long to startup on main thread so I was thinking of doing this on the background thread. But I read that you can't pass objects between the threads. The parser outputs an NSArray so is there a way to do this? I've also read that you shouldn't change UI from background thread but this array will load a table view.

推荐答案

NSObject 课程有几种不同的实例方法,允许您在主UI线程上调用方法。 performSelectorOnMainThread:withObject:waitUntilDone:方法,例如,允许您使用您选择的对象在主线程上调用接收器的方法。

The NSObject class has several different instance methods that allow you to invoke methods on the main UI thread. The performSelectorOnMainThread:withObject:waitUntilDone: method, for instance, allows you to invoke a method of the receiver on the main thread with the object of your choice.

这里有一些代码可以帮助您入门:

Here's some code to get you started:

-(void) dataDoneLoading:(id) obj {
    NSMutableArray *array = (NSMutableArray *) obj;
    // update your UI
    NSLog(@"done");
}

-(void) myThread:(id) obj {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableArray *array = [[[NSMutableArray alloc]init ]autorelease];

    // build up your array

    [self performSelectorOnMainThread:@selector(dataDoneLoading:) withObject:array waitUntilDone:NO];

    [pool release];    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [NSThread detachNewThreadSelector:@selector(myThread:) toTarget:self withObject:nil];    
}

这篇关于我可以使用后台线程来解析数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆