Question

I'm trying to map a dictionary of strings from a JSON fetch to a KVC compliant NSManagedObject, I can successfully use setValue: forKey: but i fail to see how I can map types.

For example I shouldn't be able to set a date to any random string: Printing description of myDate: asdfsadf however it worked.

I had a look at https://stackoverflow.com/a/5345023/828859 which provided some useful answers. I can go in and create validation for every single property... but that doesn't seem very DRY because ill have to validate every date and set the out value separately each time i have a date.

I would prefer to mutate by type before I use setValue: forKey: but I don't know how to discriminate on the property type.

What I want to do:

switch([object typeforkey:key]){
   case @"NSDate":
   //...
   value = mutatedDate
   //...
}
[object setValue:value forKey:key];
Was it helpful?

Solution 2

I ended up using another dictionary for property type mapping. Then a object mapping object checks the object to be map abides by this particular protocol and uses the property type dictionary to convert each property before using setValue:forKey:.

OTHER TIPS

You can ask an object what kind of class it has been instantiated as. So you can do something like:

id myObject = [myDictionary objectForKey:key];

if ([myObject isKindOfClass:[NSDate class]]) {
    // Do stuff
}
else if ([myObject isKindOfClass:[NSString class]]) {
    // Do other stuff
}

This is because objects are structs containing a pointer with the ivar name isa pointing to an object of type Class, so you can always ask an object what kind of class it comes from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top