Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/111.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试在iOS中用另一个核心数据替换现有实体对象_Ios_Core Data - Fatal编程技术网

尝试在iOS中用另一个核心数据替换现有实体对象

尝试在iOS中用另一个核心数据替换现有实体对象,ios,core-data,Ios,Core Data,我在应用程序中使用核心数据进行存储,在应用程序中,我的“实体”可能会被修改(例如地址、城市、职务) 与更新实体的特定属性不同,我只想创建一个方法,将存储中的现有实体替换为同一实体的较新版本(没什么特别的)。在我的方法中,我想我必须获取所需的实体,但是我实际上如何进行替换呢?这就是我困惑的地方 这是我的相关代码: -(void)updateUser:(User *)user { // Create fetch request NSFetchRequest

我在应用程序中使用核心数据进行存储,在应用程序中,我的“实体”可能会被修改(例如地址、城市、职务)

与更新实体的特定属性不同,我只想创建一个方法,将存储中的现有实体替换为同一实体的较新版本(没什么特别的)。在我的方法中,我想我必须获取所需的实体,但是我实际上如何进行替换呢?这就是我困惑的地方

这是我的相关代码:

    -(void)updateUser:(User *)user {

        // Create fetch request
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:_managedObjectContext];
        [fetchRequest setEntity:entity];

        // Create predicate
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"userid == %@", user.userid];
        [fetchRequest setPredicate:pred];

        // Create fetched results controller
        NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:nil]; 
        self.fetchedResultsController = theFetchedResultsController;
        _fetchedResultsController.delegate = (id)self;

        //what do I do next? 

        NSError *error;

        if (![_managedObjectContext save:&error]) {

            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);

        }

   }

正如我所说,我只是想用新的实体替换现有的实体。如何做到这一点?

我不认为替换对象比更改属性更简单

但要实现您想要的功能,您需要这样的代码:

// I don't know the class for YourEntity, 
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
    // handle fetch error
} else {
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"User" inManagedObjectContext:_managedObjectContext];
    YourEntity *newEntity = [[YourEntity alloc] initWithEntityDescription:entityDescription insertIntoManagedObjectContext:_managedObjectContext];
    // change settings on 'newEntity'

    for (YourEntity *recordToDelete in results) {
        [_managedObjectContext deleteItem:recordToDelete];
    }
    [_managedObjectContext save:&error];
    if (error) {
        // handle save error
    }
}