Check if NSEntityDescription key exists

I need to check if the NSEntityDescription key NSEntityDescription before trying to set the value. I have a data dictionary from JSON and you do not want to try to set 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]; } 
+4
source share
3 answers

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

NSEntityDescription has a method called attributesByName that returns a dictionary with your attribute names and the 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]; } } 
+12
source

Check this,

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

+5
source

I think you are asking if you want to check if appOject is responding to a property. In this case:

 if([appointmentObject respondsToSelector:NSSelectorFromString(key)])... 

The getter equivalent is the Name property. The setter equivalent is specified as process_name.

-1
source

Source: https://habr.com/ru/post/1401228/


All Articles