Objective C - respondsToSelector for dynamic properties

这一生的挚爱 提交于 2019-12-05 18:46:00

[[MyObject class] respondsToSelector:...] asks whether the metaobject responds to that selector. So, in effect, it asks whether there is a class method with that selector. Your code would return YES if you had:

+ (NSString *)myProperty;

It returns NO because you have the equivalent of the instance method:

- (NSString *)myProperty;

You need to call respondsToSelector: on an instance of your class.

You could normally use instancesRespondToSelector: directly on the metaclass (so, [MyObject instancesRespondToSelector:...]) but Core Data synthesises the relevant method implementations only when you create an object, so that's a non-starter. You could however create an instance via the normal NSEntityDescription route and test respondsToSelector: on that.

Since it's all Core Data, an alternative would be to ask the NSManagedObjectModel for the relevant NSEntityDescription via its entitiesByName dictionary and inspect the entity description's propertiesByName dictionary.

The only cases I've required this has been to set things dynamically so I am only looking for the setter. I am just composing the signature for the setter and then testing that it exists and then using it.

NSArray * keys = [myObject allKeys];
for(NSString * key in keys)
{
    NSString * string = [NSString stringWithFormat:@"set%@:", [key capitalizedString]];
    SEL selector = NSSelectorFromString(string);
    if([myObject respondsToSelector:selector] == YES)
    {
        id object = [dict objectForKey:key];

        // To massage the compiler's warnings avoid performSelector
        IMP imp = [card methodForSelector:selector];
        void (*method)(id, SEL, id) = (void *)imp;
        method(myObject, selector, object);
    }
}

This code satisfies a need where you may not be digesting all the data you receive in the dictionary. In this case it was sparse json, so some data may not always exist in the json so stepping thru myObjects attributes looking for their corresponding key would just be a lot of wasted effort.

Are you synthesizing the property in the class file?

@interface SomeClass : NSObject
{
    @property (nonatomic, strong) NSString *myProperty
}
@end


@implementation SomeClass

    @synthesize myProperty;

@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!