1

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

1
  • Why do you need to have an NSArray variable have a particular name? Commented Sep 15, 2010 at 5:52

3 Answers 3

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.