开发者

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 a开发者_如何学运维vailable. 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?


You can inspect NSManagmentObject though NSEntityDescription:

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


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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜