0

I have some parsing code I'm using for serialising and deserialising objects from our web service and I've hit a bit of a problem when serialising booleans.

The serialisation looks like this:

 - (NSDictionary *)dictionaryRepresentationWithMapping:(NSDictionary *)mappingDictionary
{
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];

    for (id key in[mappingDictionary allKeys])
    {
        id value = [self valueForKey:key];

        if ((value != [NSNull null]) && (![value isKindOfClass:[NSNull class]]) && (value != nil))
        {
            [dictionary setObject:value forKey:mappingDictionary[key]];
        }
    }

    return [NSDictionary dictionaryWithDictionary:dictionary];
}

The problem is that when I call valueForKey: on my NSManagedObject and then add this to my dictionary I end up with the value being set as if I was calling:

[dictionary setObject:@1 forKey:mappingDictionary[key]];

instead of:

[dictionary setObject:@YES forKey:mappingDictionary[key]];

This means that when I turn this into JSON, in the next stage, I'm sending 1 instead of true to the server.

So what I need is a way of retaining the fact that this is an NSNumber representing a bool as opposed to a number. I've tried asking for the class but I just get back NSNumber. Is there a way I can retain this automatically or failing that, is there a way I can consult the model to see what the attribute type was set to?

Mark Bridges
  • 8,228
  • 4
  • 50
  • 65
  • The underline class that manges boolean is __NSCFBoolean but I would not recommend a check with it, since NSNumber is a class cluster – Andrea Jul 02 '15 at 09:32
  • Take a look here http://stackoverflow.com/questions/2518761/get-type-of-nsnumber – Andrea Jul 02 '15 at 09:36

2 Answers2

2

Each entity has its metadata stored in NSEntityDescription and NSAttributeDescription. You can access them from NSManagedObject in a following way:

//you can put this inside the for loop
NSAttributeDescription *attributeDescription = self.entity.attributesByName[key];
if(attributeDescription.attributeType == NSBooleanAttributeType) {
  //it is a boolean attribute
}
Michał Ciuba
  • 7,876
  • 2
  • 33
  • 59
0

When sending a call to the server, you could do like this: [dict setValue:[NSNumber numberWithBool:YES] forKey:mappingDictionary[key]]; ; Or another way, you can model server side to retain its value as Boolean, and at that time, just need to send like this [dict setValue:YES] forKey:mappingDictionary[key]];

Hope it could help

Nghia Luong
  • 790
  • 1
  • 6
  • 11
  • This correctly produces a key which will be output as a bool in JSON. However, my problem is that I've got a serialisation method in an abstract superclass so I need the parsing to infer the type from the object. – Mark Bridges Jul 02 '15 at 12:24