我正在编写一个简单的应用程序,允许用户向数据库添加条目。数据显示在UITableView中。我无法弄清楚的是如何使用tableview的滑动到删除功能从数据库中删除一条记录。我知道代码采用这种方法:
-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
}
但我不知道如何获取填充已刷过的单元格的数据库记录。
我有一种方法可以在用户点击导航栏上的按钮时删除所有单元格:
-(void)deleteAll {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Parameters" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *managedObject in items) {
[context deleteObject:managedObject];
}
if (![context save:&error]) {
}
[self.tableView reloadData];
}
但我不知道如何自定义此代码以一次删除一条记录。任何帮助我入门的人都将不胜感激。
我也有这种方法......我认为这会永久删除记录但不会......
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[self.arr removeObjectAtIndex:indexPath.row];
[self.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
}
[self.tableView reloadData];
}
答案 0 :(得分:0)
要从带有动画的表中删除特定行,请执行以下操作:
//I am passing 0,0 so you gotta pass the row that was deleted.
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0]
[self.yourTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
要从核心数据中删除,请执行以下操作:
YourCustomModel *modelObj;
NSManagedObjectContext *context= yourmanagedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"YourCustomModel" inManagedObjectContext:context]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"yourField == %@", passTheFieldValueOfTheRowDeleted];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
if ([results count]>0)
{
modelObj = (Customers *)[results objectAtIndex:0];
}
[context deleteObject:modelObj];
if (![context save:&error])
{
NSLog(@"Sorry, couldn't delete values %@", [error localizedDescription]);
}
答案 1 :(得分:0)
你几乎就在那里..只需在获取请求中添加一个谓词。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(somePropertyInParameters = %d)",value];
[fetchRequest setPredicate:predicate];`
此外,您可以在此方法中获取滑动单元格(和参数对象)的索引路径
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath`