【问题标题】:saving manipulated values in CoreData causing error在 CoreData 中保存操作值导致错误
【发布时间】:2018-04-07 04:31:23
【问题描述】:

我在core-data 中有一个名为Record 的实体。问题是我在操作后无法保存对象,如下所示:

extension Records {
@nonobjc public class func createFetchRequest() -> NSFetchRequest<Records> {
    return NSFetchRequest<Records>(entityName: "Records")
}

@NSManaged public var datetime: Date
@NSManaged public var year: Int64
@NSManaged public var month: Int16

public override func willSave() {
    super.willSave()

    if (self.datetime != nil) {

        self.year = Int64(datetime.year())
        self.month = Int16(datetime.month())
    }
}
}

extension Date {
    func month() -> Int {
        let month = Calendar.current.component(.month, from: self)
        return month
    }

    func year() -> Int {
        let year = Calendar.current.component(.year, from: self)
        return year
    }
}

这是我遇到的错误信息:

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

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    来自Apple Documentation

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

    所以在wilSave方法的情况下,在保存self.yearself.month时重新检查是否需要分配。否则在不检查的情况下为它们分配值将使willSave 再次被调用。

    //your code
    public override func willSave() {
        super.willSave()
    
            guard let dettime = datetime else {
                return
            }
    
            if self.year != Int64(datetime.year()) {
                self.year = Int64(datetime.year())
            }
    
            if self.month != Int64(datetime.month()) {
                self.month = Int16(datetime.month())
            }
        }
    // your code
    

    【讨论】:

    • 此代码导致错误“无法使用类型为 '(() -> Int)' 的参数列表调用类型 'Int64' 的初始化程序
    • 这只是类型转换错误,我只是从您的代码中复制过来的。我刚刚对您的代码添加了额外的检查,这样willSave 就不会一遍又一遍地调用。
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2016-12-14
    • 2017-08-23
    • 1970-01-01
    相关资源
    最近更新 更多