简体   繁体   English

在objective-c中动态创建变量名

[英]dynamically creating variable names in objective-c

i'm in a bit of a situation here... 我在这里有点情况......
i am passing a string to a function and in that function i need to create an array whose name is the value of the string. 我将一个字符串传递给一个函数,在该函数中我需要创建一个名称为字符串值的数组。
Say, for example: -(void) function : (NSString *) arrayName; //let arrayName = @"foo"; 比方说,例如: -(void) function : (NSString *) arrayName; //let arrayName = @"foo"; -(void) function : (NSString *) arrayName; //let arrayName = @"foo";
In this function I need to create an array named "foo" ie the value of the passed parameter. 在这个函数中,我需要创建一个名为“foo”的数组,即传递参数的值。
Can anyone help please :| 任何人都可以帮忙请:|
Thanks in advance ;) 提前致谢 ;)

That is not possible in Objective-C, but you can use eg a dictionary that maps a string to an array. 这在Objective-C中是不可能的,但您可以使用例如将字符串映射到数组的字典。

Eg assuming something like the following property: 例如,假设类似以下属性:

@property (readonly, retain) NSMutableDictionary *arrays;

... you can store an array by name: ...您可以按名称存储数组:

- (void)function:(NSString *)arrayName {
    NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil];
    [self.arrays setObject:array forKey:arrayName];
}

... and access it like so: ...并像这样访问它:

NSArray *array = [self.arrays objectForKey:arrayName];

Arrays don't have names. 数组没有名称。 Variables have names, but variables are local to their scope, so once you leave the scope of that method, having a variable named "foo" is pointless; 变量具有名称,但变量是其范围的本地变量,因此一旦离开该方法的范围,使用名为“foo”的变量是没有意义的; you can name the variable whatever you want and it will work just fine. 您可以根据需要为变量命名,它可以正常工作。 Ex: 例如:

- (void) function:(id)whatever {
  NSArray * myVariable = [NSArray arrayWithStuff....];
  //use myVariable
}

What are you really trying to do? 你真的想做什么?

C is a compiled language where any source code names (for variables, functions, etc.) are not available at runtime (except for perhaps optionally debugging, -g). C是一种编译语言,其中任何源代码名称(用于变量,函数等)在运行时都不可用(除非可选地调试,-g除外)。 The Objective C runtime adds to this the ability to look up Obj C methods and classes by name, but not objects, nor any C stuff. Objective C运行时增加了按名称查找Obj C方法和类的能力,但不是对象,也不是任何C东西。 So you're out of luck unless you build your own mini-language-interpreter structure for reference-by-name. 所以除非你建立自己的迷你语言解释器结构以供参考,否则你运气不好。 Lots of ways to do this, but simple languages usually build some sort of variable table, something like a dictionary, array, or linked-list of objects (structs, tuples, etc.) containing string name, object pointer (maybe also type, size, etc.). 有很多方法可以做到这一点,但简单的语言通常会构建某种变量表,类似于字典,数组或对象的链接列表(结构,元组等),包含字符串名称,对象指针(也许类型,大小等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM