views:

64

answers:

3

hey all,
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 ;)

+2  A: 

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];
Georg Fritzsche
+2  A: 

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?

Dave DeLong
hey thanks for your opinion... :) Actually the function is recursive in nature; so everytime i iterate through it, i want to be able to create a new array without losing the previous one...
Bangdel
@Bangdel if the method is recursive, then the object will still exist in the frame/scope in which it was created. Once you exit the recursive call, the object will still be there.
Dave DeLong
A: 

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

hotpaw2