我正在運行到索引超出範圍例外之一,在我的UITableViews
和我認爲它可能歸結爲一些多線程問題。這就是我認爲正在發生的事情:UITableViewDataSource和多線程
- 我有一個
UITableView
和它的數據源是一個普通NSMutableArray
。 - 這個支持我的
UITableView
的NSMutableArray
每隔幾秒就會更新一次API響應的內容。 - 每次更新後,都會調用
UITableView
的reloadData以確保用戶看到來自API服務器的新數據。 - 有時超出界限異常的索引被拋出。
這裏是我的代碼:
-(NSMutableArray*) currentBetEvents
{
return currentMarketId == nil ? [[BFOpenBetsModel sharedInstance] betEvents] : filteredBetEvents;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSArray *betEvents = [self currentBetEvents];
return [betEvents count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *betEvents = [self currentBetEvents];
id obj = [betEvents objectAtIndex:indexPath.section] // this is where it blows up
基本上,我得到一個異常,而試圖在索引來訪問betEvents結構的對象0
我相信的情況是:
reloadData
被調用UITableView
numberOfSectionsInTableView:
被調用,返回的值大於0.- 胭脂線程到達並清除了
UITableView
的數據源。 cellForRowAtIndexPath:
被調用並炸彈。
有什麼方法可以確保不會發生這種情況嗎?我是否需要開始在數據源上使用一些原始鎖,以確保在更新表時不會更新?
編輯 拿了再看看由currentBetEvents返回的數據結構可以如何改變,它看起來像filteredBets & betEvents可以如下面的代碼,結果被清除出:
[[NSNotificationCenter defaultCenter] postNotificationName:kUserLoggedOutNotification object:nil];
每當用戶註銷時都會發布此通知。每當用戶註銷應用程序時,我需要清除filteredBets和betEvents數組。是有可能,以下可能發生:
reloadData
被呼籲UITableView
numberOfSectionsInTableView:
調用它返回一個值> 0- 用戶註銷揭開序幕通知&送走數據結構。
cellForRowAtIndexPath:
被調用並炸彈。
感謝,
肖恩
你正在實現numberOfRowsInTableView? – rdelmar
我認爲你需要展示betEvents如何得到更新,以及你如何通知表視圖它需要更新。 – rdelmar
rdelmar - 我沒有實現numberOfRowsInTableView。只需numberOfRowsInSection和numberOfSectionsInTableView。編輯我的答案,以包含更多關於賭注數組如何更新的更多信息。謝謝。 – seanoshea