How to check if an attribute exists at run time in a subclass of NSManagedObject

How to check if an attribute exists for a specific object at runtime. I will use a property called dateAddStamp, but not all objects have this attribute. This class will serve as the basis for other entity classes ... Therefore, I want to check at runtime. If I can call [self setPrimitiveValue: xxx forKey: xxx] or not ... Thanks.

+7
source share
4 answers
BOOL hasFoo = [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil; 
+16
source

in quick

  let hasFoo = myObject.entity.propertiesByName.keys.contains("foo") 
+5
source

To improve omz's answer, you should also check if the property is an attribute (and not a relation named @ "foo"):

  BOOL hasFoo = ( [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil && ([[[myObject.entity propertiesByName] objectForKey:key] isKindOfClass:[NSAttributeDescription class]]) ) 
+3
source

Swift 3.2 Usage contains validation from an array of keys:

 if managedObject.entity.attributeKeys.contains("yourKey") { let value = managedObject.value(forKey: "youreKey") as! ClassName) } 

or use if-let:

 if let data = managedObject.value(forKey: "youreKey") { let value = data as! ClassName } 
+1
source

All Articles