开发者

How to see if a class has a property?

开发者 https://www.devze.com 2023-03-21 23:22 出处:网络
I am parsing some xml, and I update the server pretty frequently with new features. So, when I add a new tag or something, my app, which parses the data crashes when I call because the currentElementV

I am parsing some xml, and I update the server pretty frequently with new features. So, when I add a new tag or something, my app, which parses the data crashes when I call because the currentElementValue is not part of my class yet. Is there anyway to check if a 开发者_JAVA技巧class has a property, or should I just catch the exception that gets raised?

[a setValue:currentElementValue forKey:elementName];

Thanks


Very simple:

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


If you haven't overridden the standard setter and getter names you can use:

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

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

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

for its getter method.

Otherwise, if you used a syntax like:

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

when defining the property, use the corresponding name with the above syntax:

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


First you need to capitalize the first letter of your property name.

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

Then you need to make a selector that would set the property. (If you have a property called "foo" then by default the setter for this property will be called "setFoo:".)

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

Then like in sergio's answer, call:

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

Check this post to see how to get an object's properties.


for Swift5

if class_getProperty([object class], "propertyName") != nil {
    // it has that property!
}
0

精彩评论

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