使用属性名称动态访问Objective-C属性 [英] Access Objective-C property dynamically using the name of the property

查看:97
本文介绍了使用属性名称动态访问Objective-C属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know the string name of a property of an object. How would I go about getting and setting that property using the string?

推荐答案

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

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

使用:

[anObject valueForKey: @"propertyName"];

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

很明显,@"propertyName"可以是在运行时动态组成的NSString.

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

该技术称为键值编码,它是可可的基础.

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

为什么更好,是因为-valueForKey将执行装箱"该属性返回对象的任何类型所必需的操作.因此,如果该属性的类型为int,它将返回一个包含int的NSNumber实例.

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.

这更容易处理-performSelector 可以用于 happen 以适合指针的内存的类型.

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

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

这篇关于使用属性名称动态访问Objective-C属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆