0

我正在编写一个简单的应用程序,它允许用户向数据库添加条目。数据显示在 UITableView 中。我不知道如何使用表格视图的滑动删除功能从数据库中删除一条记录。我知道代码采用这种方法:

-(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];
}
4

2 回答 2

0

我使用MCSwipeTableCell进行了相同的滑动以删除功能

要使用动画从表中删除特定行,请执行以下操作:

 //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]);
}
于 2013-04-12T04:36:17.817 回答
0

你快到了.. 只需在 fetch 请求中添加一个谓词。

  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(somePropertyInParameters = %d)",value]; 
   [fetchRequest setPredicate:predicate];`

此外,您可以在此方法中获取滑动单元格(和 Parameter 对象)的索引路径

  - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath` 
于 2013-04-12T04:39:49.923 回答