在CoreData中保存操纵值会导致错误

时间:2018-04-07 04:31:23

标签: ios swift core-data

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

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.

1 个答案:

答案 0 :(得分:1)

来自Apple Documentation

  

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

因此,对于wilSave方法,请在保存self.year时重新检查&amp;需要分配self.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