【问题标题】:Xcode, ios, Set name of variable to value of another variable?Xcode,ios,将变量名称设置为另一个变量的值?
【发布时间】:2015-07-24 00:36:47
【问题描述】:

我想将一个变量的名称设置为另一个变量的值有没有其他方法可以做到这一点,因为我不认为这是方法。

NSString *myint = @"a";

NSString *([NSString stringWithFormat:@"%@", myint]) = @"something";

NSLog(@"%@", a);

【问题讨论】:

  • 您能否使用NSDictionary 实现您想要的?

标签: ios xcode nsstring


【解决方案1】:

不,你不能这样做。一旦你的代码被编译,你的变量就没有真正的名字——只有位置。您在调试器中看到的名称是由调试器用来将位置映射到名称的符号文件提供的。

键值编码可能会有所帮助,具体取决于您真正想要完成的工作。使用 KVC,您可以使用键名来引用值,而不是访问变量,就像使用字典一样。例如,如果您有一个具有属性foo 和bar 的对象,则可以执行以下操作:

NSString *key = @"foo";
[myObject setValue:@(5) forKey:key];

您甚至可以覆盖 -setValue:forKey: 以便它接受任何键并记住值(这正是字典的作用)。

您可以使用stringification operator 朝另一个方向发展(将变量设置为另一个变量的名称),但它有点老套,而且通常不是很有用。简而言之,以 # 为前缀的宏参数用作文字字符串,而不是被评估。所以你会创建一个这样的宏:

#define string(x) #x

然后你会在代码中的某个地方使用它,如下所示:

int foo = 5;
NSLog("The name of the variable is %s and its value is %d.", string(foo), foo);

结果如下:

The name of the variable is foo and its value is 5.

【讨论】:

    【解决方案2】:

    我同意 Paulw11。您可以定义一个 NSMutableDictionary 来按键保存所有变量。我认为编译器无法使用在运行时确定的句柄。但是你可以达到同样的效果。

    比如说,变量句柄和值都是NSString,那么你可以这样做。

    NSMutableDictionary *myObjects = [[NSMutableDictionary dictionary] init];
    
    NSString variableName = @"myString";
    
    [myObjects setObject @"Variable value" forKey: variableName];
    
    NSLog("Variable %@ has value %@.", variableName, [myObjects objectForKey: variableName]);
    

    【讨论】:

    • 我相信如果你用 @(insert integer here) 替换 @["variable value"] ,它仍然可以工作,但使用整数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2021-08-22
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多