2010-07-23 77 views
0

嗨,我收到來自udp的2000數據,並在tableview中顯示值。什麼是最簡單的方法來做到這一點?如何從NSDictionary顯示UITableView單元格中的數據?

現在我使用兩個nsthreads和一個線程通過udp接收數據並將其存儲在NSMutableDictionary中。另一個線程使用這些字典值更新tableview。但它崩潰了我的應用程序。

下面是一些代碼我用

予存儲的接收值這樣

NSMutableDictionary *dictItem 
CustomItem *item = [[CustomItem alloc]init]; 
item.SNo =[NSString stringWithFormat:@"%d",SNo]; 
item.Time=CurrentTime; 
[dictItem setObject:item forKey:[NSString stringWithFormat:@"%d",SNo]]; 
[item release]; 

委託方法我用和我用CustomTableCells顯示數據作爲列副。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
return 1; 

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [dictItem count]; 
} 



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *identifier = @"CustomTableCell"; 
    CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:identifier]; 
    if (cell == nil) 
    { 
     cell = [[[CustomTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease]; 
    } 
    NSArray *keys = [dictItem allKeys]; 
    CustomItem *item = [dictItem objectForKey:[keys objectAtIndex:indexPath.row]]; 
    cell.SNo.text = item.SNo; 
    cell.Time.text = item.Time; 
    return cell; 
} 

的errror是

終止應用程序由於未捕獲的異常 'NSGenericException',原因: '***收集了同時列舉了突變。' 2010-07-23 02:33:07.891 Centrak [2034:207]堆棧:( 42162256, 43320108, 42161198, 43372629, 41719877, 41719345, 9948, 3276988, 3237662, 3320232, 3288478, 71153942, 71153189, 71096786, 71096114, 71296742, 41650770, 41440069, 41437352, 51148957, 51149154,) 拋出'NSException'實例後終止調用

任何人都可以幫我嗎?

在此先感謝.......

+0

沒有辦法來幫助您提供您提供的信息。也許如果你可以爲你的表視圖數據源委託方法發佈一些代碼,你從數據字典中提取數據並放入單元格。 – 2010-07-23 06:44:27

回答

0

你可能必須使用鎖,因爲當你從表視圖訪問您的字典,它或許與其它線程突變。 嘗試查看NSLock文檔。在突變你的字典之前做[myLock lock];和變異之後做[myLock unlock];。在其他線程中類似:在枚舉字典之前,執行[myLock lock];並獲取所有值之後再執行[myLock unlock];myLock是一個NSLock對象,必須在您的線程之間共享。

0

可變集合本質上不是線程安全的,所以如果您將它們與多個線程一起使用,則必須先創建一個不可變副本。例如,如果你想通過你的NSMutableDictionary所有鑰匙,迭代,你可以這樣做(假設你的NSMutableDictionary被稱爲mutableDictionary):

NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:mutableDictionary]; 

for(id key in dictionary) { 
    // Do anything you want to be thread-safe here. 
} 

如果你不想複製的字典,我想你可以使用鎖或只是@synchronized指令如下:

@synchronized(mutableDictionary) { 
    // Do anything you want to be thread-safe here. 
} 

欲瞭解更多信息,請看看蘋果的文件關於多線程和線程安全的對象:http://developer.apple.com/mac/library/documentation/cocoa/conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html

相關問題