重新排序TableView时如何更改CoreData的索引?

时间:2017-04-05 05:31:33

标签: ios objective-c iphone core-data tableview

请仔细阅读代码并告诉我这里的错误。

TableViewController.m

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:context];

    NSFetchRequest *fetchrequest = [[NSFetchRequest alloc]initWithEntityName:entity];
    _devices = [[context executeFetchRequest:fetchrequest error:nil]mutableCopy];
    [self.tableView reloadData]; // When TableView is reloading the data in tableview updating according to the data stored via CoreData.

}


- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

    if (fromIndexPath != toIndexPath ) {

        NSManagedObjectContext *context = [self managedObjectContext];
        NSManagedObject *device = [self.devices objectAtIndex:fromIndexPath.row];

        NSString *str1 = [device valueForKey:@"text1"];

        NSLog(@"%@",str1);
        [self.devices removeObject:device];

        [self.devices insertObject:device atIndex:[toIndexPath row]];

//        int i = 0;
//        for (NSManagedObject *mo in self.devices)
//        {
//            NSManagedObject *new = [self.devices objectAtIndex:i];
//            NSString *check = [new valueForKey:@"text1"];
//            NSLog(@"%@",check);
//            NSString *check1 = [new valueForKey:@"text2"];
//            NSLog(@"%@",check1);
//            NSString *check2 = [new valueForKey:@"text3"];
//            NSLog(@"%@",check2);
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text1"]] forKey:@"text1"];
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text2"]] forKey:@"text2"];
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text3"]] forKey:@"text3"];
//            i++;
//        }


        NSError *error;

        if(![context save:&error]){
            NSLog(@"%@ %@",error, [error localizedDescription]);
        }

    }

}

我有实体名称:设备和列名:text1,text2,text3

我不想对Core Data中的数据进行排序,实际上我想在TableView中移动行,我想更新列text1,text2,text3中保存的数据的索引。总共,tableview中有5行,我只想更新相对于更新的tableview索引的值的索引。

1 个答案:

答案 0 :(得分:0)

检查以下教程

http://www.cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller/

简而言之,你需要添加" displayIndex"您尝试重新加载的对象的属性