试图保存NSManagedObjectContext不起作用 [英] trying to save NSManagedObjectContext not working

查看:47
本文介绍了试图保存NSManagedObjectContext不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试解决这个问题已有2天了.尝试保存时,我总是收到错误消息.

I have been trying to figure out this problem for 2 days now. I keep getting an error when I try to save.

//self.data is NSManagedObject. kAppDelegate.moc is the managed object context.
self.data = [NSEntityDescription insertNewObjectForEntityForName:@"Data"
                                 inManagedObjectContext:kAppDelegate.moc];

[self.data setValue:[NSNumber numberWithBool:NO] forKey:@"isit"];
[self.data setValue:@"" forKey:@"name"];

NSError *error;
if(![self.data.managedObjectContext save:&error])
{
    NSLog(@"Save did not complete successfully. Error: %@",
    [error localizedDescription]);
}

不过,当我运行它时,它会出现在控制台中:

When I run it though, this appears in the console:

"CoreData:错误:从上下文中删除托管对象0x10935d4c0(0x10935d420)之后,对其进行突变."

"CoreData: error: Mutating a managed object 0x10935d4c0 (0x10935d420) after it has been removed from its context."

这:

保存未成功完成.错误:(空)

Save did not complete successfully. Error: (null)

我不知道为什么会这样,或者为什么错误是"null".

I can't figure out why this is happening, or why the error is "null".

推荐答案

还有另一种方式来引发"CoreData:错误:在将托管对象从其上下文中删除之后,对其进行突变……".消息.

There is another way to provoke the "CoreData: error: Mutating a managed object ... after it has been removed from its context." message.

  • 如果您具有多层核心数据堆栈
  • 您对前景中的托管对象有很强的引用
  • 后台线程更新同一核心数据对象

当更新冒泡到前台线程时,它将使您的对象无效.您需要检测到并检索新版本.

When the update bubbles up to the foreground thread it invalidates your object. You need to detect that and retrieve the new version.

在缓存对象中保留弱引用.然后编写一个getter,检查该缓存对象是否为nil,并检索该对象的新版本.

Hold a weak reference in a cache object. Then write a getter that checks that cache object for nil and retrieves the new version of the object.

weak var cachedObject: NSManagedObject?

var object: NSManagedObject {

    get {

        objc_sync_enter( self )
        defer {

            objc_sync_exit( self)
        }

        guard nil == cachedObject else {

            return cachedObject!
        }

        guard let object = // **** retrieve object here ****

            fatalError( "managed object does not exist" )
        }

        cachedObject = object

        return cachedObject!
    }

    set {

        cachedObject = newValue
    }
}

或者,您可以每次在getter中检索对象.

Or, you could just retrieve the object every time in the getter.

这篇关于试图保存NSManagedObjectContext不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆