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
My approach to resolving this issue was to create an NSManagedObject
subclass and handle the substitution of empty strings for NULL values in awakeFromInsert
. I then set all entities as children of this subclass rather than children of NSManagedObject
. The assumption here is that I want every string attribute within a given entity to be set to an empty string by default (it wouldn't work, or would at least require extra logic, if you wanted some to remain NULL within the same entity).
There's probably a more efficient way of doing this, but since it's only called upon entity creation, I don't think it is too much of a performance hit.
- (void)awakeFromInsert {
[super awakeFromInsert];
NSDictionary *allAttributes = [[self entity] attributesByName];
NSAttributeDescription *oneAttribute;
for (NSString *oneAttributeKey in allAttributes) {
oneAttribute = [allAttributes objectForKey:oneAttributeKey];
if ([oneAttribute attributeType] == NSStringAttributeType) {
if (![self valueForKey:[oneAttribute name]]) {
[self setValue:@"" forKey:[oneAttribute name]];
}
}
}
}