warrenm
warrenm

Reputation: 31782

How to determine whether subclass of NSManagedObject has a particular property at runtime

I'm accustomed to using doesRespondToSelector: and instancesRespondToSelector: to determine at runtime whether objects have certain methods available. However, when using Core Data, I am not seeing the expected behavior for my @dynamic properties. For example, if I have a sortOrder property on my class, I can use the Objective-C runtime to see that this property exists at runtime. But if I ask the relevant Class object whether instancesRespondToSelector:, I get back NO. If I use the runtime to enumerate the available methods, none of my dynamic getters/setters appear in the list, which is consistent, but not what I expected.

My question, then, is: without using runtime inspection, is there an easy way to determine if an instance of an NSManagedObject subclass responds to getter/setter selectors that correspond to its @dynamic properties?

Upvotes: 3

Views: 1430

Answers (2)

Massimo Oliviero
Massimo Oliviero

Reputation: 1044

You can inspect NSManagmentObject though NSEntityDescription:

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

Upvotes: 13

Chris Wagner
Chris Wagner

Reputation: 21003

I have used the following method on NSManagedObject objects to retrieve a list of it's properties. Maybe it 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];
}

Upvotes: 4

Related Questions