如何将变量名转换为字符串?
例子:
由此:
NSString *someVariable
int otherVariable
我想得到一个带有变量实际名称的 NSString ,无论它是什么类型。
所以,对于上面的两个变量,我想得到它们的名字(someVariable,otherVariable)。
如何将变量名转换为字符串?
例子:
由此:
NSString *someVariable
int otherVariable
我想得到一个带有变量实际名称的 NSString ,无论它是什么类型。
所以,对于上面的两个变量,我想得到它们的名字(someVariable,otherVariable)。
我设法用这个代码片段解决了我的问题:
导入 objc 运行时
#import <objc/runtime.h>
您可以使用以下方法枚举属性:
- (NSArray *)allProperties
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
希望它可以帮助某人。
只需在变量名周围添加“...”。IE
"someVariable"
"otherVariable"
获取字符串(作为一个const char*
。)如果你想要一个NSString*
,使用
@"someVariable"
@"otherVariable"
在宏中,您可以使用构造#...
将引号...取消引用宏变量,例如
#define MyLog(var) NSLog(@"%s=%@", #var, var)
以便
MyLog(foo);
扩展为
NSLog(@"%s=%@", "foo", foo);
这些是 C 声明,C 没有自省能力来给你想要的东西。
您可能会编写一个预处理器宏,它既可以声明一个变量,也可以用第一个变量的名称声明和初始化第二个变量。
但这引出了一个问题,即为什么你需要这种程度的内省。