Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSEntityDescription key exists

I need to check if an NSEntityDescription key exists before trying to set the value. I have a dictionary of data from JSON and don't want to try setting keys that do not exist in my object.

Appointment *appointmentObject = [NSEntityDescription insertNewObjectForEntityForName:@"Appointments" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
for (id key in dict) {
    // Check if the key exists here before setting the value so we don't error out.
        [appointmentObject setValue:[dict objectForKey:key] forKey:key];
}
like image 452
Bot Avatar asked Dec 04 '22 04:12

Bot


2 Answers

you should not check for selectors. Imagine a key called entity or managedObjectContext. The NSManagedObject class definitely responds to those selectors, but the best thing that will happen if you try to assign something wrong to those is that your code crashes instantly. A little less luck and something like this destroys the complete core data file, and all the user data.

NSEntityDescription has a method named attributesByName which returns a dictionary with your attribute names and corresponding NSAttributeDescriptions. So these keys are basically all the attributes you can use.

Something like this should work:

Appointment *appointmentObject = [NSEntityDescription insertNewObjectForEntityForName:@"Appointments" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
NSArray *availableKeys = [[appointmentObject.entity attributesByName] allKeys];
for (id key in dict) {
    if ([availableKeys containsObject:key]) {
        // Check if the key exists here before setting the value so we don't error out.
        [appointmentObject setValue:[dict objectForKey:key] forKey:key];
    }
}
like image 106
Matthias Bauch Avatar answered Dec 28 '22 13:12

Matthias Bauch


Check this,

BOOL hasFoo = [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil;

like image 29
Arun Avatar answered Dec 28 '22 14:12

Arun