2014-11-04 123 views
0

我想从名为Friends的实体中删除一行。我有一个UITableView其中dataSource来自实体Friends。我可以从tableview中删除一条记录,但我也想从数据库中删除关联的行。从CoreData删除记录

我在这里可能会错过什么?

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

我刚开始学习xcode,但是如何将选定的表格单元实例化为NSManagedObject? – zyrae 2014-11-04 12:04:02