【问题标题】:How to access the property of own class with its name as a string [duplicate]如何以字符串形式访问自己的类的属性[重复]
【发布时间】: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

【问题讨论】:

标签: objective-c properties


【解决方案1】:

你想要valueForKey。这是Key-Value coding(KVC):

for (NSUInteger i = 1; i <= 3; i++) {
    NSString *key = [NSString stringWithFormat:@"image%u", i];
    UIImageView *value = [self valueForKey:key];
}

【讨论】:

  • 对不起,我已经编辑了这个问题,使其更清楚。
  • @Roohul 原理是一样的; value 的类型从 NSString 更改为 UIImageView 是全部。
  • 非常感谢。效果很好。
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2019-11-01
  • 2011-02-23
相关资源
最近更新 更多