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
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)
}
}
}
}
...
}
A simpler solution based on Scott Marks answer to avoid syntax errors:
First, temporarily set the default value to be easy to find, something like here you are
. Open with any text editor the contents
file inside the .xcdatamodel
bundle inside the .xcdatamodeld
bundle. Then just do a search with replacing the string "here you are"
with the ""
in this file.
The migration took place without problems.