2011-11-22 35 views
2

我正在嘗試在UITableCell(設計爲IB)的子類中正確設置觸摸UIButton事件的目標,該子類將刪除該單元。然而,當在模擬器跑了,我得到以下錯誤:在目標方法中傳遞UIButton參數nil

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* - [__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'

它得到的方法很好,但它始終是NSArray的arrayWithObject線後立即崩潰。看起來這是因爲傳遞給目標方法的按鈕始終爲零。

我假設這是一個內存問題,但我很困惑如何解決它。我是否需要完全編程創建單元以使其工作,或者是否有一種簡單的方法來以某種方式將按鈕操作的目標指定爲Interface Builder的主ViewController?

這裏就是細胞在視圖控制器創建:

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


    if(tableView==songList){ 


     static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; 

     SongCell *cell = (SongCell *)[tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; 

     if(cell == nil) { 
      NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SongCell" owner:self options:nil]; 
      cell = [nib objectAtIndex:0]; 
      [cell.addButton addTarget:self action:@selector(addToPlaylist:) forControlEvents:UIControlEventTouchUpInside]; 


     } 

     NSUInteger row = [indexPath row]; 
     cell.songname.text = @"test";//[songListData objectAtIndex:row]; 

     return cell; 
    } 

    return nil; 

} 

而這裏的目標方法:

-(void)addToPlaylist:(id)button{ 

    SongCell *song = (SongCell *)[(UIButton *)button superview]; 
    NSIndexPath *indexPath = [self.songList indexPathForCell:song]; 
    NSArray *rowToMove = [NSArray arrayWithObject:indexPath]; 

    [self.songList beginUpdates]; 
    [self.songList deleteRowsAtIndexPaths:rowToMove withRowAnimation:UITableViewRowAnimationFade]; 
    [self.songList endUpdates]; 

} 

,你可以提供任何幫助將不勝感激。

+1

嘗試記錄'button'和'indexPath'。我的第一個猜測是Interface Builder已經自動調整了視圖層次結構,以便你的按鈕的超級視圖不再是'SongCell'本身。 – Tommy

回答

0

錯誤是b/c indexPath必須爲零。你的代碼示例中有許多可疑的事情。你的執行SongCell是什麼?將子視圖添加到單元格時,應將其添加到單元格的contentView,並直接添加到單元格中。 [button superview]沒有返回單元,因此indexPath的下一行返回nil

一些其他的想法:

  1. 它看起來像你只需要行號按下按鈕時。您可以將rowIndex + 1存儲在按鈕標記屬性中,然後檢索它 - addToPlaylist:中的1。您需要+/- b/c標籤屬性應該> 0。或者,使用具有屬性的UIButton子類來存儲您的indexPath

  2. 如果您要通過deleteRowsAtIndexPaths:withRowAnimation:刪除一行,您需要先從數據源中刪除同一行以維護表的完整性。

  3. 如果您只進行一次刪除,則不需要beginUpdates/endUpdates

+0

由於我的UIButton只是在UITableCell的內部,所以它確實沒有任何邏輯意義,但是按鈕的超級視圖的超級視圖的超級視圖終於讓我獲得了子類型的TableCell。 ><這使我走上正確的道路,所以感謝您的幫助。 另外,感謝代碼的其他部分的信息。我只是一個初學者(不打算髮布這個應用程序),我絕對可以使用我能得到的所有幫助! – Luke