我正在尝试覆盖 tableView:commitEditingStyle:editingStyleforRowAtIndexPath:
并且无法执行删除 NSManagedObject
的实际实例在该行中表示。
Apple 表示应该使用以下代码(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
}
}
最佳答案
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 显示索引 0 为 1。
您的错误消息表明您仍然有一个 NSArray 而不是变量 eventsArray
你可以像这样从 NSArray 中创建一个 NSMutableArray :
NSMutableArray *arMu = [[NSMutableArray alloc] initWithArray:someNSArray];
关于iphone - 如何从数据源中删除 NSManagedObject 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8483853/