C lens - responsible for the SoSelector dynamic properties

Currently, I am facing a problem to check if an object property (NSManagedObject) exists or not.

Unfortunately method

[[MyObject class] respondsToSelector:@selector(myProperty)]; 

always returns NO.

I think this is because the property generated by CoreData is a new style ala property

 @property (nonatomic, strong) NSString *myProperty 

So, have any ideas how to solve this problem?

I would really appreciate all your suggestions;)

Thanks in advance! Alex

+4
source share
3 answers

[[MyObject class] respondsToSelector:...] asks if the meta object is responding to this selector. So, in reality, he asks if a class method exists with this selector. Your code will return YES if you have:

 + (NSString *)myProperty; 

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

 - (NSString *)myProperty; 

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

You can usually use instancesRespondToSelector: directly in the metaclass (so [MyObject instancesRespondToSelector:...] ), but Core Data only synthesizes the corresponding method implementations when creating an object, so it does not start. However, you could create an instance using the regular NSEntityDescription route and respondsToSelector: test.

Since everything is Core Data, an alternative would be to set the NSManagedObjectModel for the corresponding NSEntityDescription through its entitiesByName dictionary and check the propertiesByName description dictionary.

+15
source

The only cases I required was to install things dynamically, so I am only looking for an installer. I simply draw a signature for the setter, and then test that it exists, and then use 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 warnings avoid performSelector IMP imp = [card methodForSelector:selector]; void (*method)(id, SEL, id) = (void *)imp; method(myObject, selector, object); } } 

This code satisfies the need that you cannot digest all the data that you receive in the dictionary. In this case, it was rare json, so some data may not always exist in json, so going to the myObjects attributes looking for their corresponding key will be just a lot of effort.

+1
source

Are you synthesizing a property in a class file?

 @interface SomeClass : NSObject { @property (nonatomic, strong) NSString *myProperty } @end @implementation SomeClass @synthesize myProperty; @end 
0
source

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


All Articles