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

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

    I resolved this by overriding the getter for my field - if it contains null, I return an empty string instead:

    -(NSString *)unit {
        if ([self primitiveValueForKey:@"unit"] == NULL) {
            return @"";
        } else {
            return [self primitiveValueForKey:@"unit"];
        }
    }
    

    So far it seems to be doing the trick, and I would imagine it wouldn't impact migrations (although I don't know enough about them to say for sure). I don't really care whether there's a null or an empty string in the db, after all - so long as I get "" instead of null when I ask for the field.

提交回复
热议问题