【问题标题】:Is there a way to dynamically allocate or assign values to ivars of a class at runtime in Cocoa / Cocoa Touch?有没有办法在运行时在 Cocoa / Cocoa Touch 中为类的 ivars 动态分配或分配值?
【发布时间】:2013-05-15 08:53:57
【问题描述】:

我确信我们可以在运行时动态确定类的 iVar。有没有办法在运行时分配确定的 iVar? TIA..

【问题讨论】:

    标签: objective-c cocoa-touch cocoa objective-c-runtime


    【解决方案1】:

    简短的答案和您可能想要的答案是:
    [obj setValue:@"woof" forKey:@"dog"];

    还有闲聊……

    您可以使用运行时查找一个类的所有 iVar:

    Ivar * class_copyIvarList(Class cls, unsigned int *outCount)

    例如:

    id someObj; //assigned elsewhere
    unsigned int count = 0;
    Ivar * iVarList = class_copyIvarList([someObj class],&count);
    for(;count>0;count--)
    {
        Ivar testVar = iVarList[count]; 
        //do something with test Ivar
    }
    free(iVarList);
    

    我几乎可以肯定你永远不会想要这样做,除非是在调试场景中......内省私有框架等。

    或者,如果您知道 iVar 的名称,您可以使用:
    Ivar object_setInstanceVariable(id obj, const char *name, void *value)[obj setValue: @"woof" forKey:@"dog"] 的更客观的方式最终将无法设置 iVar。

    您可能会做的,而我过去必须做的就是内省属性列表:

    类似地调用:objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount) 这对于复制未知对象和调试很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多