How to determine if a subclass of NSManagedObject has a specific property at run time

I’m used to using doesRespondToSelector:it instancesRespondToSelector:to determine at runtime whether objects have certain methods. However, when using Core Data, I do not see the expected behavior for my properties @dynamic. For example, if I have a property sortOrderin my class, I can use the Objective-C runtime to see that this property exists at run time. But if I ask the appropriate object Class, instancesRespondToSelector:I will be back NO. If I use the runtime to list the available methods, none of my dynamic getters / setters appear on the list, which is consistent, but not what I expected.

So my question is: without using a run-time check, is there an easy way to determine if an instance of a subclass responds to the NSManagedObjectgetter / setter selectors matching its properties @dynamic?

+3
source share
2 answers

I used the following method for objects NSManagedObjectto get a list of its properties. Perhaps he will point you in the right direction ....

- (NSMutableArray *) propertyNames: (Class) class { 
    NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
    unsigned int propertyCount = 0;
    objc_property_t *properties = class_copyPropertyList(class, &propertyCount);

    for (unsigned int i = 0; i < propertyCount; ++i) {
        objc_property_t property = properties[i];
        const char * name = property_getName(property);
        [propertyNames addObject:[NSString stringWithUTF8String:name]];
    }
    free(properties);
    return [propertyNames autorelease];
}
+4
source

You can check NSManagmentObject, but NSEntityDescription:

- (BOOL)hasPropertyWithName:(NSString *)name
{
    NSEntityDescription *desc = self.entity;
    return [desc.attributesByName objectForKey:name] != nil;
}
+12
source

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


All Articles