动态字段属性名称目标C.

时间:2015-11-20 17:46:58

标签: objective-c

我对这门语言很陌生,但对别人有很好的把握。

我想知道如何在目标c中动态访问字段名称属性。

类似的东西:

self.bottomText.text = @"foo";

转到:

NSString *bottomText = @"bottomText";

self[bottomText].text = @"foo";

我可以理解如何设置这样的属性(根据下面的复制标记):

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

但在我看来,它要么必须遵守:

[self.bottomText setValue:@"foo" forKey:@"text"];

这并没有真正解决问题,或类似的事情:

[self setValue:bottomText forKey:property].text = @"foo";

不知道属性是什么。

或者也许:

[self valueForKey:bottomText].text = @"Test";

但没有爱。

这个超级困惑。

2 个答案:

答案 0 :(得分:1)

好吧,假设awaitbottomText(因为它有UILabel属性...),你可以这样做:

text

或者如果你真的想要它在一行:

SEL selector = NSSelectorFromString(@"bottomText");
UILabel *label = (UILabel *)[self performSelector:selector];
label.text = @"Test";

答案 1 :(得分:1)

我很不确定,我是否理解你的Q正确。但是simle KVC应该可以解决你的问题:

NSString *bottomText = @"bottomText";
[self valueForKey:bottomText].text = @"foo";

NSString *property = @"bottomText.text";
[self setValue:@"foo" forKeyPath:property];

此外,self课程可以实施keyed subscription

相关问题