Elliott D'Alvarez
Elliott D'Alvarez

Reputation: 1237

CoreData / NSManagedObject mapping, how to check if the object property supports the passed type

I have written some code to map data from a server to my CoreData objects, and this all works as expected. However, I get a lot of unrecognized selectors warnings in the log. This is basically due to the server having the same key names for different object types. My code is below:

for (id key in dict)
    {
        if ([UsefulFunctions objectContainsData:dict[key]])
        {
            if (mapping[key])
            {
                SEL selector = NSSelectorFromString(mapping[key]);

                if ([entity respondsToSelector:selector])
                {
                    @try {
                        // try and set the value, might not work if dict[key] is unexpected type
                        [entity setValue:dict[key] forKey:mapping[key]];
                    }
                    @catch (NSException *exception) {
                        // deal with the exception
                    }
                }
            }
        }
    }

Basically what this code does is cycle through the 'dict' of objects passed by the server. It checks that they contain data, and then creates the selector based on the mapping dictionary I have setup (example below):

@"id" : @"nID",

It then checks if the entity (NSManagedObject) responds to the created selector (nID for example), and then tries to apply data to check it's validity. Like mentioned this all works fine, however, due to the mismatched types I get lots of annoying errors printed in the log. Is there a better way to test if the NSManagedObject can handle the data passed to it?

For example, nID holds a number but if the server passes a string the app would crash. So I have wrapped this in a try / catch to stop this happening. Is there any way of doing the same without a try / catch or is this the correct approach? I don't just want to go suppressing warnings.

Thanks for any help.

Upvotes: 0

Views: 128

Answers (1)

Wain
Wain

Reputation: 119031

This is the purpose of NSAttributeDescription that you can get to via the propertiesByName of the NSEntityDescription for the entity. It will tell you the attributeType that you can use for validation / comparison. See also attributeValueClassName which you may be able to leverage.

Upvotes: 1

Related Questions