Core Data Boolean property NSNumber doesn't remember it's boolean

后端 未结 3 1016
暗喜
暗喜 2021-01-12 12:57

I have a model with a property that looks like this:

\"enter

When I set its va

相关标签:
3条回答
  • 2021-01-12 13:30

    Core Data dynamically generates getter and setter methods for all attributes (and relationships) of managed object classes. These accessor methods are different from the "usual" @synthesized accessor methods which are backed up by an instance variable.

    In particular, if you set an attribute and then retrieve the attributes value again, you can get an object that is different from the "original" object. The following test shows this, foo1 is an instance of a Core Data entity with the Boolean attribute "show":

    NSNumber *yes = @YES;
    NSLog(@"yes = %p, type = %s", yes, [yes objCType]);
    foo1.show = yes;
    NSNumber *val = foo1.show;
    NSLog(@"val = %p, type = %s", val, [val objCType]);
    

    Output:

    yes = 0x16e595c, type = c
    val = 0x744c150, type = i
    

    So even if you set the attribute to a c = char encoded number, the getter method returns a i = int encoded number.

    This test was done in the iOS Simulator. Interestingly the same test, running on OS X 64-bit, returns a c = char encoded number.

    Therefore, the actual encoding of Boolean and other scalar attributes in Core Data objects should probably be treated as an implementation detail of Core Data.

    If you need to check the Core Data type as defined in the model, you can use the objects entity description instead of objCType:

    NSEntityDescription *entity = [foo1 entity];
    NSAttributeDescription *attr = [[entity attributesByName] objectForKey:@"show"];
    NSAttributeType type = [attr attributeType];
    if (type == NSBooleanAttributeType) {
        NSLog(@"Its a Boolean!");
    }
    
    0 讨论(0)
  • 2021-01-12 13:35

    What is up with that?

    From the documentation:

    Note that number objects do not necessarily preserve the type they are created with.

    That's another inconsistency-for-optimization in Cocoa.

    0 讨论(0)
  • 2021-01-12 13:37

    Its stored as a NSNumber - by the way @YES is creating a NSNumber like

    [NSNumber numberWithBool:YES]

    so to get the bool back out you do:

    [isResolved boolValue]

    (you can avoid this by ticking the Use Scalar Properties when you create your models)

    0 讨论(0)
提交回复
热议问题