使用属性的名称动态访问Objective-C属性

qua*_*ano 25 reflection objective-c key-value-coding declared-property

我知道对象属性的字符串名称.我将如何使用字符串获取和设置该属性?

bbu*_*bum 51

虽然@weichsel是正确的,但还有更好的方法.

使用:

[anObject valueForKey: @"propertyName"];
Run Code Online (Sandbox Code Playgroud)

[anObject setValue:value forKey:@"propertyName"];
Run Code Online (Sandbox Code Playgroud)

显然,@"propertyName"可以是NSString在运行时动态组合的.

这种技术称为键值编码,是Cocoa的基础.

为什么这样做更好是因为-valueForKey将执行必要的操作以"装箱"属性返回到对象中的任何类型.因此,如果属性是类型int,它将返回NSNumber包含int 的实例.

这是很容易处理- performSelector为该工种发生以适应指针的值的内存.

请注意,还有-setValue:forKey:.