我正在尝试从名为Friends
的实体中删除一行。我有一个UITableView
,其中dataSource来自实体Friends
。我可以从tableview中删除一条记录,但我也想从数据库中删除相关的行。
我可以在这里找到什么?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
friendsList = [[NSMutableArray alloc] init];
[self fillTableView];
}
-(void) fillTableView
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Friends"];
NSError *requestError = nil;
NSArray *friends = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
if([friends count] > 0)
{
NSUInteger counter = 1;
for(Friends *thisFriend in friends)
{
[friendsList addObject:thisFriend.fullname];
counter++;
}
}
else
{
NSLog(@"No Friends entity.");
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"AllFriends";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [friendsList objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete)
{
[friendsList removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
非常感谢任何帮助。谢谢你。
答案 0 :(得分:0)
array:- friends contains the records of Friends entity so you have to keep this array.
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete)
{
[friendsList removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// delete from event entity --
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:yourObject]; //array friends object at indexPath.row
[self.managedObjectContext save:nil];
[tableView reloadData];
}
}