Reputation: 4732
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.
Upvotes: 1
Views: 4201
Reputation: 668
It is better to use NSOperation class to do that job. You can find a nice example named "LazyTableImages" at XCode documentation. It is uses a NSOperation to parse a XML
Upvotes: 0
Reputation: 9876
ofcourse we can pass objects to thread... please go through the link which shows how to process heavy task in background...
Upvotes: 0
Reputation: 2683
You can always pass objects between threads.
Use the following code to create a thread and pass the object to it.
[NSThread detachNewThreadSelector:@selector(myThreadSelector:) toTarget:self withObject:myObject];
After the thread function is over you can pass the data back to the main thread using
[self performSelectorOnMainThread:@selector(myMainSelector:) withObject:myReturnObject waitUntilDone:NO];
you can pass the output NSArray from the parser to myMainSelector: and reload the tableview in it.
-(void)myMainSelector:(id)sender
{
NSArray *arr = sender;
tableDataArray = [NSArray arrayWithArray:arr];
[yourTableView reloadData];
}
You can show an activity indicator while you are in the thread method.
Upvotes: 8
Reputation: 13696
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];
}
Upvotes: 2