我正在尝试覆盖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
}
}
答案 0 :(得分: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为索引0显示1
您的错误消息表明您仍然有一个NSArray而不是变量eventsArray
您可以从NSArray中创建一个NSMutableArray,如下所示:
NSMutableArray *arMu = [[NSMutableArray alloc] initWithArray:someNSArray];