gpt4 book ai didi

objective-c - 在 Cocoa/Cocoa Touch 中,有没有一种方法可以在运行时为类的 ivars 动态分配或赋值?

转载 作者:行者123 更新时间:2023-12-03 16:41:49 24 4
gpt4 key购买 nike

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

最佳答案

简短的答案,您可能想要的答案是:
[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);

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

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

你可能会做的,也是我过去必须做的,就是内省(introspection)属性列表:

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

关于objective-c - 在 Cocoa/Cocoa Touch 中,有没有一种方法可以在运行时为类的 ivars 动态分配或赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com