简体   繁体   English

如何为CoreData中的NSManaged属性赋予初始值?

[英]How to give an initial value to NSManaged property in CoreData?

I use Swift. 我用Swift。 I have a CoreData, and it has a string attribute called days. 我有一个CoreData,它有一个名为days的字符串属性。 I want to assign a default value to this. 我想为此分配一个默认值。 I tried it in my CoreData model class but it gives an error saying "NSManaged property cannot have an initial value" . 我在我的CoreData模型类中尝试了它,但它给出了一个错误,说“NSManaged属性不能有初始值”

This is what I tried. 这是我试过的。

@NSManaged var daysAvailable:String = "M"

It's actually really easy. 这其实很简单。 Just override the awakeFromInsert method for your NSManagedObject subclass. 只需覆盖NSManagedObject子类的awakeFromInsert方法。

class Person: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var age: NSNumber

    override func awakeFromInsert() {
        super.awakeFromInsert()
        setPrimitiveValue(21, forKey: "age")
        setPrimitiveValue("Bob", forKey: "name")
    }
}

According to the awakeFromInsert documentation : 根据awakeFromInsert 文档

If you want to set attribute values in an implementation of this method, you should typically use primitive accessor methods (either setPrimitiveValue:forKey: or—better—the appropriate custom primitive accessors). 如果要在此方法的实现中设置属性值,通常应使用原始访问器方法(setPrimitiveValue:forKey:或 - 更好 - 适当的自定义原始访问器)。 This ensures that the new values are treated as baseline values rather than being recorded as undoable changes for the properties in question. 这可确保将新值视为基准值,而不是将其记录为相关属性的可撤消更改。

Override wake form insert to initialise core data object 覆盖唤醒表单插入以初始化核心数据对象

 Override func awakeFromInsert()
 {
   super.awakeFromInsert()
   self.daysAvailable = "M"  
  } 

check following link for more details: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdManagedObjects.html 请查看以下链接以获取更多详细信息: https//developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdManagedObjects.html

If it a static value, you can set it in the CoreData model editor in xcode. 如果它是静态值,您可以在xcode中的CoreData模型编辑器中进行设置。 No need to use 'awakeFromFetch' for that 无需使用'awakeFromFetch'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM