我正在爲用戶輸入時給出結果的iPhone創建字典應用程序。我使用線程(NSThread)來更新UITableView,以便主線程不被阻塞。但是,當UITableView詢問數據源的行數(tableView:numberOfRowsInSection :)並返回,比如說10時,就會發生崩潰。然後它詢問數據源的單元格0-9(tableView:cellForRowAtIndexPath :)。但是當它要求單元7時,數據源已經改變了,現在它只有5行,從而導致崩潰。使用線程更新UITableView
這是我如何解決這個問題:
我在init()方法創建一個NSLock。
而且這裏是數據源的樣子:
- (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;
}
這裏是我用來更新表的代碼:
[tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
它徹底解決了死機問題。不過,我認爲它可能效率不高,因爲數據源在每次詢問單元時都必須鎖定/解鎖。而我上面提到的情況並不經常發生。有沒有人有更好的想法如何有效地解決這個問題?
非常感謝!
你不應該更新在另一個線程的UI。 – rickharrison 2010-07-30 20:06:45
Rick,我必須在另一個線程中搜索結果,因爲搜索方法非常慢,我不希望它阻塞主線程。你能解釋一下如何在不使用其他線程的情況下實現這一目標嗎? – ifvc 2010-07-30 20:14:52
使它更快。你究竟在尋找什麼?! – mvds 2010-07-30 20:17:51