无论如何要从变量名中获取字符串? [英] Anyway to get string from variable name?
本文介绍了无论如何要从变量名中获取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我要上课
@interface Person : NSObject { NSString *name; }
我需要在我的课程中获取NSString的名称
I need to get the name of NSString's within my class
Person *person = [[Person alloc] init];
NSLog(@"Name of variable %s\n", _NameofVariable_(person->name));
感谢您的回答,这是我从答复中得出的解决方案
//returns nil if property is not found
-(NSString *)propertyName:(id)property {
unsigned int numIvars = 0;
NSString *key=nil;
Ivar * ivars = class_copyIvarList([self class], &numIvars);
for(int i = 0; i < numIvars; i++) {
Ivar thisIvar = ivars[i];
if ((object_getIvar(self, thisIvar) == property)) {
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
break;
}
}
free(ivars);
return key;
}
推荐答案
You can get the names of a class's instance variables with the Objective-C runtime API function class_copyIvarList
. However, this is rather involved, rarely done and almost never the best way to accomplish something. If you have a more specific goal in mind than mere curiosity, it might be a good idea to ask about how to accomplish it in Objective-C.
另外,person.name
并没有在Objective-C中指定实例变量-这是一个属性调用.实例变量将为person->name
.
Also, incidentally, person.name
doesn't specify an instance variable in Objective-C — it's a property call. The instance variable would be person->name
.
这篇关于无论如何要从变量名中获取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文