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

后端 未结 8 854
鱼传尺愫
鱼传尺愫 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:38

    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]];
                }
            }
        }
    }
    

提交回复
热议问题