2014-11-04 134 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