Access Objective-C property dynamically using the name of the property

ε祈祈猫儿з 提交于 2019-11-27 14:57:53

While @weichsel is correct, there is a better way.

Use:

[anObject valueForKey: @"propertyName"];

and

[anObject setValue:value forKey:@"propertyName"];

Obviously, @"propertyName" can be an NSString that is dynamically composed at runtime.

This technique is called Key Value Coding and is fundamental to Cocoa.

Why this is better is because -valueForKey will do what is necessary to "box" whatever type the property returns into an object. Thus, if the property is of type int, it'll return an NSNumber instance containing the int.

This is much easier to deal with -- performSelector will only work for types that happen to fit into a pointer's worth of memory.

Note that there is also -setValue:forKey:.

@synthesize propertyName automates the generation of getter and setter methods.

The compiler generates

  • - (id)propertyName;
  • - (void)setPropertyName;

If you have a selector as NSString, you can use performSelector:NSSelectorFromString.
e.g.:
[object performSelector:NSSelectorFromString(@"propertyName") ...]

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