Hi guys,
I am creating a dictionary application for iPhone that gives result while the users are typing. I use threads (NSThread) to update the UITableView so that the main thread is not blocked.
However, a crash happens when the UITableView asks the data source for the number of rows ( tableView:numberOfRowsInSection:) and I return, say, 10. Then it asks the data source for cells 0-9 (tableView:cellForRowAtIndexPath:). But by the time it asks for cell 7, the data source has already changed, and it now has only 5 rows, thus causing a crash.
Here is how I solve the problem:
I create a NSLock in the init method.
And here is what the data source looks like:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[lock lock];
if (indexPath.row < [results count]) {
cell.textLabel.text = [results objectAtIndex:indexPath.row];
}
[lock unlock];
return cell;
}
And here is the code that I use to update the table:
[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
It solves the crash problem completely. However, I think that it might not be efficient because the data source has to lock/unlock every time it is asked for a cell. And the case that I mentioned above doesn't happen that often. Does anyone have a better idea of how to solve this problem efficiently?
Thank you very much!