How do I know if a class has a property?

I am parsing some xml, and I pretty often update the server with new features. So, when I add a new tag or something else, my application that parses the data crashes when called because currentElementValue is not yet in my class. Is there anyway to check if a class has a property, or should I just catch the exception that occurs?

[a setValue:currentElementValue forKey:elementName];

thank

+5
source share
3 answers

Very simple:

if (class_getProperty([object class], "propertyName")) {
    // it has that property!
}
+19
source

If you have not redefined the default settings and recipient names, you can use:

 if ([object respondsToSelector:@selector(setProp:)]) {

for a property setter method called "prop", or:

 if ([object respondsToSelector:@selector(prop)]) {

for the method of obtaining it.

, :

@property (assign, getter=hasProp) BOOL prop;

:

 if ([object respondsToSelector:@selector(hasProp)]) {
+8

.

NSString *capitalizedProperty = [NSString stringWithFormat:@"%@%@", [[propertyName substringToIndex:1] uppercaseString], [propertyName substringFromIndex:1]];

, . ( "foo", "setFoo:".)

SEL propertySetter = NSSelectorFromString([NSString stringWithFormat:@"set%@:",capitalizedProperty]);

, sergio, :

if ([object respondsToSelector:propertySetter])
{
    [object setValue:value forKey:propertyName];
}

, , .

0

All Articles