2012-07-30 44 views
0

创建ID我正在使用的所有实例变量的列表如下:从伊瓦尔

Ivar *vars = class_copyIvarList([property class], &varCount); 

我的问题是如何创建从伊瓦尔一个id?即恢复NSString或NSDictionary等。

+0

的Objective-C的目的不是用这种活力的记在心里。你想做什么? – bbum 2012-07-30 13:54:10

回答

2

您只需使用object_getIvar()函数。 事情是这样的:

uint varCount; 
Ivar *vars = class_copyIvarList([property class], &varCount); 

// Get the first one (out of an instance of this class) 
// Of course you could just iterate and get each one 
id var = object_getIvar(property, vars[0]); 

// Free the array when you're done 
free(vars); 
+0

这个假设伊娃是类型(id)。请注意,object_getIvar()实际上已被弃用,因为它实际上不适用于许多类型。 – bbum 2012-07-30 13:53:53

+0

@bbum是的,这是正确的。我不知道,也看到乔纳森的评论。感谢您的高举。 – Alladinian 2012-07-30 13:58:02

2

这种方法可以简化您的转换代码:

id obj = [p valueForKey:[NSString stringWithUTF8String:ivar_getName(anIvar)]]; 
... 
+2

这种方法比'object_getIvar()'方法允许更简洁的代码,因为它会自动包装其类型不是对象的ivars(例如,'int' ivar将被封装在'NSNumber'中,'NSValue'中的'struct'等等 – 2012-07-30 12:41:31