我有一个包含单个实体对象的核心数据模型。然后我将这些对象加载到一个数组中,并将它们显示在具有默认单元格样式的表中。在导航栏中有一个删除按钮,当选择一行(例如对象)并单击此按钮时,它应该删除核心模型中的行和相应的对象。我见过删除行的示例,但每行显示一个删除按钮。我想在导航栏中只有一个按钮,并能够控制从中删除行。我已经尝试过下面的代码,但它不起作用。我无法找到一种方法来识别delete方法中选择的行。任何帮助表示赞赏。
在tableviewcontroller类的viewdidload中:
UIBarButtonItem *delButton = [[UIBarButtonItem alloc]
initWithTitle:@"Del"
style: UIBarButtonItemStyleBordered
target: self
action:@selector(delItemToArray)];
self.managedObjectContext = ((ecoAppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"FavoritesInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.resultType = NSDictionaryResultType;
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"name", nil]];
NSError *error=nil;
self.favArr=[self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error!=nil) {
NSLog(@" fetchError=%@,details=%@",error,error.userInfo);
}
self.favName = [self.favArr valueForKey:@"name"];
//Delete Item To table array and delete object to data core model
- (void)delItemToArray {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
[context deleteObject:appDelegatee.favoritesInfo]; // favoritesInfo is the NSManagedObject
NSIndexPath *indexPath;
[favName removeObjectAtIndex:indexPath.row];
[appDelegatee saveContext]; // to save changes in the core data model
[self.tableView reloadData];
}
错误:
[__NSArrayI removeObjectAtIndex:]: unrecognized selector sent to instance 0x8852b90
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI removeObjectAtIndex:]: unrecognized selector sent to instance 0x8852b90'
答案 0 :(得分:1)
您可能会收到Incompatible pointer types initializing 'NSMutableArray *' with an expression of type 'NSArray *'
这里的警告
self.favArr=[self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
您应该使fetched数组可变,以便从中删除对象。你可以像
那样做self.favArr = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
同时更改此
self.favName = [self.favArr valueForKey:@"name"];
到
self.favName = [[self.favArr valueForKey:@"name"]mutableCopy];