【发布时间】:2016-06-29 12:49:43
【问题描述】:
我正在寻找一种通过名称访问我的财产的方法。 例如,我在特定类中有 3 个属性为
@property (nonatomic, weak) UIImageView *image1;
@property (nonatomic, weak) UIImageView *image2;
@property (nonatomic, weak) UIImageView *image3;
我有一个方法
- (void)accessProperty:(NSString *)propertyName{
//image1, image2 or image3 will be passed here.
//how can I access the property with its name ?????
}
任何帮助将不胜感激。
让我更准确地提到我的需要。
我有 3 个imageView,但我想将图像设置为特定的 imageView,其名称与我传递给该方法的名称匹配。例如,如果我将方法称为
[self accessProperty:@"image1"]; 那么它应该只将图像设置为imageView1
【问题讨论】:
-
我相信属性有
IBOutlet否则weak对象将在初始化后释放。要使用名称访问您的属性,请使用[self valueForKey:propertyName]KVC,它将返回整个对象。 -
Access ObjC property dynamically using the name of the property 确实会告诉您如何做到这一点,但the other question 会为您提供更重要的信息:为什么不应该以及该怎么做。另见:Create multiple numbered variables based on a int