bangdel
bangdel

Reputation: 2553

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";
In this function I need to create an array named "foo" i.e the value of the passed parameter.
Can anyone help please :|
Thanks in advance ;)

Upvotes: 1

Views: 1937

Answers (3)

hotpaw2
hotpaw2

Reputation: 70743

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). 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. 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.).

Upvotes: 0

Georg Fritzsche
Georg Fritzsche

Reputation: 99122

That is not possible in Objective-C, but you can use e.g. a dictionary that maps a string to an array.

E.g. 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];

Upvotes: 2

Dave DeLong
Dave DeLong

Reputation: 243156

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; 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?

Upvotes: 2

Related Questions