【问题标题】:Dynamic object property name in objective C目标 C 中的动态对象属性名称
【发布时间】:2012-02-20 12:46:44
【问题描述】:

我正在尝试使用动态名称访问对象的属性...这可能吗?

就像在 javascript 中一样:

var foo = 'bar';
appr.templates[foo];

这个想法是访问appr.templates.bar

【问题讨论】:

    标签: iphone objective-c cocoa-touch key-value-coding


    【解决方案1】:

    您可以为此使用valueForKey:

    像这样:

    NSString *foo = @"bar";
    
    [appr.templates valueForKey: foo]
    

    【讨论】:

      【解决方案2】:

      您可以使用键值编码或 KVC 来做到这一点,请参阅方法 -valueForKeyPath:。例如:

      @interface Foo
      @property(strong) NSString *bar;
      @end
      
      // Somewhere in other code, foo is an instance of Foo
      NSString *bar = [foo valueForKeyPath:@"bar"];
      

      【讨论】:

        猜你喜欢
        • 2010-12-20
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        相关资源
        最近更新 更多