2013-03-24 77 views
0

我用核心數據中的數據加載tableview。 它獲取文本加載。 每個單元格都有一個uiimageview。當表調用cellForRow:它要麼設置圖像隱藏或不隱藏,(這取決於核心數據說,它應該是。)UITableView單元格給出了錯誤的信息

代碼:

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

static NSString * identifier = @"identifier"; 

self.cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 

HuntingRifleGuns *handguns = [self.tableArray objectAtIndex:indexPath.row]; 

NSString *brandModel = [[handguns.brand stringByAppendingString:@" "] stringByAppendingString:handguns.model]; 

self.cell.mainLabel.text = brandModel; 

self.cell.nicknameLabel.text = handguns.nickname; 
//Right below me, is where is set the imageView to hidden, or not hidden. 
self.cell.alert.hidden = handguns.showBadge.boolValue; 

self.cell.alert.image = [UIImage imageNamed:@"tvicon.png"]; 

return self.cell; 
} 

我的問題是:如果我有1在桌子視圖上的單元格,它的工作原理非常完美,但是如果我在桌子上有更多的單元格,它就會起作用。

我要檢查,看看是否單元格的形象被隱藏,當它被刪除:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 

if (editingStyle == UITableViewCellEditingStyleDelete) {   

    if (!self.cell.alert.isHidden) { 


     NSLog(@"showing"); 

    } 
else{ 

NSLog(@"Not showing"); 
} 
    ......... 

但是,當它的測試中,它不總是做正確的事情。它只是隨機打印出showingnot showing。我知道它是否應該顯示,因爲它顯示在單元格上的圖像。這可能是什麼原因? 只是一個側面說明,用戶可以設置圖像隱藏或不隱藏在不同的意見,但tableview總是顯示正確的數據,這意味着它顯示圖像正確可見或隱藏,只是當我測試它,它doesnt總是工作。

感謝您的幫助!

回答

2

您已創建@property,名爲cell。這是行不通的。

你應該只使用一個UITableViewCell變量或一個與你的自定義單元格:

CustomCell *cell = [tableView dequeue...]; 

而且,你的字符串的處理,是不是很高效利用內存。使用stringWithFormat代替:

cell.mainLabel.text = [NSString stringWithFormat:@"%@ %@", 
     handguns.brands, handguns.model]; 

此外,檢查是否視圖是隱藏的,告知您的應用程序邏輯是非常不好的做法。相反,你應該有一個健壯的數據模型,而不是查詢數據模型。在你的情況下,你應該查詢適當的handguns對象是否有圖像。

1

奇怪的是,您將分出的單元格分配給self上的某個屬性。這幾乎肯定不會是你認爲的那樣,因爲單元格是以非確定性方式從-tableView:cellForRowAtIndexPath:中請求的。您應該將已出隊的單元格分配給局部範圍的變量。使用-tableView:commitEditingStyle:forRowAtIndexPath:的參數來檢索要處理的單元格。例如:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    if ([[[cell textLabel] text] isEqualToString:@"foo"]) { 
     NSLog(@"showing"); 
    } else{ 
     NSLog(@"Not showing"); 
    } 
    } 
} 

此外,調試一個問題,像這樣的時候,它往往是有用的,以減少問題仍然引起該問題的最簡單的可能的事情。如果不使用自定義單元格或您在那裏進行的任何操作,而是使用簡單的UITableViewCell以及它的默認外觀,會發生什麼情況。而不是隱藏或顯示您添加到單元格中的圖像視圖,您只需將其默認文本更改爲「foo」或「bar」或類似的東西?如果您仍然遇到問題,那麼您的代碼將變得更加簡單易於解釋。如果您不再遇到問題,那麼您可以一次性將自定義內容添加回原來的內容,直到找到可以解決問題的修改爲止。