2012-05-22 61 views
1

我有一個UITableView填充了從NSUserDefaults讀取的mutablearray。我希望用戶能夠刪除一些存在的項目。下面是具體的編輯方法和這裏的代碼是整個文件:http://pastebin.com/LmZMWBN9UITableView提交編輯錯誤

當我點擊「編輯」,並刪除項目的應用程序崩潰和我回去:

終止應用程序由於未捕獲例外 'NSInternalInconsistencyException',原因是: ' - [__ NSCFArray removeObjectAtIndex:]:變異的方法發送到不可變對象'

我的具體問題是,我是什麼錯誤在這裏幹什麼?

// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (editingStyle == UITableViewCellEditingStyleDelete) { 

    // edit list of names 
    if ([listOfNames count] >= 1) { 
     [tableView beginUpdates]; 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     [listOfNames removeObjectAtIndex:[indexPath row]]; 

     // write updated listofnames to nsuserdefaults 
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

     [[NSUserDefaults standardUserDefaults] setObject:listOfNames forKey:@"My Key"]; 

     [defaults synchronize]; 

     if ([listOfNames count] == 0) { 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     } 
     [tableView endUpdates]; 
    } 


} 
else if (editingStyle == UITableViewCellEditingStyleInsert) { 
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
} 
} 

回答

3

您的listOfNames實例變量是不可變的,因此您無法從中刪除對象。

變化:

listOfNames = [[defaults objectForKey:@"My Key"] copy]; 

listOfNames = [[defaults objectForKey:@"My Key"] mutableCopy]; 

-viewWillAppear:viewDidLoad方法。

+0

Gah,將錯誤版本的文件複製/粘貼回實時項目中。我一直在說..「我知道我改變了這一點」..謝謝@graver。將它選爲正確的,當它讓我。 – TerryG