CoreData - can't set empty string as default value for attribute

后端 未结 8 856
鱼传尺愫
鱼传尺愫 2021-02-06 22:08

I have an entity in my datamodel with a string attribute that is currently optional, and I\'d like to convert this to a required attribute with a default value of the empty stri

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 22:43

    Here is the Swift solution based on David Ravetti's answer and edelaney05's comment. In addition, I added optionality check.

    This solution works fine in my projects.

    class ExampleEntity: NSManagedObject {
    
        ...
    
        override func awakeFromInsert() {
            super.awakeFromInsert()
            for (key, attr) in self.entity.attributesByName {
                if attr.attributeType == .stringAttributeType && !attr.isOptional {
                    if self.value(forKey: key) == nil {
                        self.setPrimitiveValue("", forKey: key)
                    }
                }
            }
        }
    
        ...
    }
    

提交回复
热议问题