Core-Data willSave:方法 [英] Core-Data willSave: method

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

问题描述

我在实体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.' ***

所以,我想知道什么是设置 modifyDate 的值的最好方法?

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将继续被调用,直到你的程序崩溃。

If you want to update a persistent property value, you should typically test for equality of any new value with the existing value before making a change. If you change property values using standard accessor methods, Core Data will observe the resultant change notification and so invoke willSave again before saving the object’s managed object context. If you continue to modify a value in willSave, willSave will continue to be called until your program crashes.

例如,如果您设置了最后修改的时间戳,您应该检查您之前是否在同一个保存操作中设置它,或者现有时间戳不小于比当前时间的小增量。通常,最好为所有保存的对象计算一次时间戳(例如,响应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以反映最小delta您预期的储存要求之间。

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

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

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