Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C threads and GUI updates problem

I'm developing an iOS app with a view containing a TableView. Some method receives data from the web, opens a new thread to calculate information and inserts a row into the table at run time with the method: insertRowsAtIndexPaths.

Now if a lot of data is coming at once, the table may update itself after a few insertions and not after each one, and thats provokes an exception saying that the number of rows in section isn't right (that's because it thinks it should have an increment of one row but the threads already inserted the array of data some more cells).

Even if I make a lock on the insertion to the datasource array and the insertRowsAtIndexPaths method, it's still do the same.

NSLock *mylock = [[NSLock alloc] init];
[mylock lock];

[array addObject:object];

[tableView insertRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationLeft];

[mylock unlock];

help please,

Thank you!

like image 479
AMM Avatar asked Jan 20 '23 18:01

AMM


1 Answers

you have to run this method on the main thread. All User Interface interaction has to be done on the main thread.

Let's say your method looks like this:

- (void)addSomeObject:(id)object {
    [array addObject:object];
    [tableView insertRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationLeft];
}

and you are calling it like this:

[self addSomeObject:anObject];

then you would change this call to something like this:

[self performSelectorOnMainThread:@selector(addSomeObject:) withObject:anObject waitUntilDone:NO];
like image 123
Matthias Bauch Avatar answered Jan 27 '23 19:01

Matthias Bauch