Unable to replace one Entity by another in Core Data in iOS

综合技术 2017-12-04 阅读原文

I am working on an iOS application where I am using Core Data for storage. In my store, every entity will be unique, and I'm building a function where I replace one existing entity with another that I pass in. Here is an example of an entity that I pass:

NSManagedObjectContext *context = [[MyDB sharedInstance] managedObjectContext];

    User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];

    NSNumber *userNumber = 12345;

    user.id = userNumber;
    user.name = @"John Doe";
    user.email = @"[email protected]";
    user.createdDate = [NSDate date];

    [[MyDB sharedInstance] updateUser:user];

Inside my Core Data storage, I have an identical Entity already, except that the email address is "[email protected]". My update at the moment looks like this:

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

    NSError *error;
    NSManagedObjectContext *context = [[MyDB sharedInstance] managedObjectContext];

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

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

    NSArray *results = [context executeFetchRequest:fetchRequest error:&error];

    if (error) {
        // handle fetch error
    } else {

        user = [[User alloc] initWithEntity:entity insertIntoManagedObjectContext:context];

        for (User *recordToDelete in results) {

            [context deleteObject:recordToDelete];//record gets deleted here, which is fine


        [context save:&error]; //this doesn't save the new entity that I passed in

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


    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id=%@", 12345];
    [fetchRequest setPredicate:pred];

    NSArray *items = [context executeFetchRequest:fetchRequest error:&error];

    for (User *testObject in items) {

        NSLog(@"ID: %@, Name: %@, Email: %@, Created Date: %@", [testObject id], [testObject name], [testObject email], [testObject createdDate]);



The problem is that the above function deletes the existing record in the store, however, it fails to add the new entity that replaces it. Can someone show me how to correct this?

Thanks in advance to all who reply.

You are not calling save method on managed object context. Call save method on managedObjectContext in which you are creating new object. [managedObjectContext save:nil];

Recmonded way is. First fetch object depending on number, and delete it. After that create managed object. At the end call Save on context.

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!


IOS Root View Controller viewDidAppear: ... In my iOS app I want to run a series of operations in my Root View Controller after it has already appeared on the screen. However, it seems that the ...
Game Center not recognizing my game I am making a test app to learn using Game Center. I've read many tutorials and questions here in stack overflow and i'm on the right way. Now, i ha...
iOS之沙盒路径 介绍 每一个APP都有一个存储空间,就是沙盒。APP之间不能相互通信。沙盒根目录结构:Documents、Library、temp。 iOS的沙盒下面主要包含该以下三个文件: Home.png 路径是这样的: // 获取沙盒主目录路径 ...
MOSEC议题解读 | Build your own iOS kernel debugger... 议题概要 Ian Beer在这次议题中介绍了如何针对零售版的iOS设备开发一个内核调试器。议题的内容会涵盖ARM64底层在XNU中的异常处理,KDP远程调试的协议以及如何在不修改内核代码的前提下打造一个支持设置断点的本地内核调试器。 作者介绍 Ian Beer在Googl...
代码处理iOS的横竖屏旋转 一、监听屏幕旋转方向 在处理iOS横竖屏时,经常会和UIDeviceOrientation、UIInterfaceOrientation和UIInterfaceOrientationMask这三个枚举类型打交道,它们从不同角度描述了屏幕旋转方向。 1、UIDeviceOrientation:...