本文介绍了核心数据 willSave: 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Entity A 中有一个属性 modificationDate. 我想在保存 NSManagedObject 时设置它的值.但是,如果我尝试在 NSManagedObject willSave: 方法中执行此操作,则会出现错误:

I have an attribute modificationDate in my Entity A. I want to set its value whenever NSManagedObject is saved. However, if i try to do that in NSManagedObject willSave: method, i get an error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Failed to process pending changes before save.  The context is still dirty after 100 attempts.  Typically this recursive dirtying is caused by a bad validation method, -willSave, or notification handler.' ***

那么,我想知道,设置 modificationDate 值的最佳方法是什么?

So, i'm wondering, what's the best way to set the value of modificationDate?

推荐答案

来自 willSave 的 NSManagedObject 文档:

From the NSManagedObject docs for willSave:

如果要更新持久属性值,通常应该在进行更改之前测试任何新值与现有值的相等性.如果您使用标准访问器方法更改属性值,Core Data 将观察结果更改通知,因此在保存对象的托管对象上下文之前再次调用 willSave.如果你继续修改 willSave 中的一个值,willSave 将继续被调用,直到你的程序崩溃.

例如,如果您设置了最后修改的时间戳,您应该检查您之前是否在同一个保存操作中设置了它,或者现有的时间戳不小于当前时间的小增量.通常,最好为所有正在保存的对象计算一次时间戳(例如,响应 NSManagedObjectContextWillSaveNotification).

For example, if you set a last-modified timestamp, you should check whether either you previously set it in the same save operation, or that the existing timestamp is not less than a small delta from the current time. Typically it’s better to calculate the timestamp once for all the objects being saved (for example, in response to an NSManagedObjectContextWillSaveNotification).

所以也许是这样的:

-(void)willSave {
    NSDate *now = [NSDate date];
    if (self.modificationDate == nil || [now timeIntervalSinceDate:self.modificationDate] > 1.0) {
        self.modificationDate = now;
    }
}

您可以在哪里调整 1.0 以反映您预期的保存请求之间的最小增量.

Where you can adjust the 1.0 to reflect the minimum delta between your expected save requests.

这篇关于核心数据 willSave: 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:20