2011-12-13 71 views
0

我正在嘗試覆蓋tableView:commitEditingStyle:editingStyleforRowAtIndexPath:,並且無法實現刪除該行中表示的NSManagedObject的實際實例。如何從數據源中刪除NSManagedObject實例?

蘋果公司說,它應該用下面的代碼(Shown Here)來完成:

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

if (editingStyle == UITableViewCellEditingStyleDelete) { 

    // Delete the managed object at the given index path. 
    NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row]; 
    [managedObjectContext deleteObject:eventToDelete]; 

    // Update the array and table view. 
    [eventsArray removeObjectAtIndex:indexPath.row]; 
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; 

    // Commit the change. 
    NSError *error = nil; 
    if (![managedObjectContext save:&error]) { 
     // Handle the error. 
    } 
} 
} 

當我在我的應用程序模擬天生此示例代碼,每一行的工作,除了一行。一行是:[bowlerArray removeObjectAtIndex:indexPath.row];。我得到錯誤「接收器類型'NSArray',例如消息沒有用選擇器'removeObjectAtIndex'聲明一個方法。

這一行代碼應該是什麼?

注意:我的線NSManagedObject *eventToDelete = [bowlerArray objectAtIndex:indexPath.row];工作得很好。

更新:發佈我的實際代碼:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (editingStyle == UITableViewCellEditingStyleDelete) { 
    // Delete the row from the data source 

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
    NSManagedObjectContext *moc = [appDelegate managedObjectContext]; 

    NSManagedObject *objectToDelete = [bowlerArray objectAtIndex:indexPath.row]; 
    [moc deleteObject:objectToDelete]; 

    [bowlerArray removeObjectAtIndex:indexPath.row]; 

    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
} 
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 
} 
} 

回答

4

NSArray是不變的,所以你不能修改它。
removeObjectAtIndex不是NSArray API的一部分,因爲它會修改它。
您需要NSMutableArray才能做到這一點。


如果我這樣做:

NSMutableArray *arMu = [NSMutableArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", nil]; 
[arMu removeObjectAtIndex:0]; 
self.bigLabel.text = [arMu objectAtIndex:0]; 

的bigLabel是顯示1的指數爲0。
你的錯誤信息提示,你仍然有一個的NSArray而不是一個NSMutableArray爲可變eventsArray


您可以從一個的NSArray像這樣做出的NSMutableArray:

NSMutableArray *arMu = [[NSMutableArray alloc] initWithArray:someNSArray]; 
+0

進行該更改後,嘗試刪除時出現以下錯誤。由於未捕獲異常'NSInvalidArgumentException',原因:' - [_ PFArray removeObjectAtIndex:]:發送到實例0xb65fb60的無法識別的選擇器'終止應用程序。 – tarheel

+0

你可以發佈該更改,因爲 - (void)removeObjectAtIndex:(NSUInteger)index'是一個NSMutableArray的有效選擇器。 –

+0

在我的viewWillAppear:方法,其中我的bowlerArray通過行'bowlerArray = [moc executeFetchRequest:request error:&error]填充;'有一個警告'NSArray *'指派給'NSMutableArray * _strong'的不兼容指針類型。 – tarheel