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];
}
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];
}
}
Check this,
BOOL hasFoo = [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With