1

Possible Duplicate:
Objective C Equivalent of PHP’s “Variable Variables”

I have created a method in objective C which looks like this:

- (void) startBuildingXArray: (NSMutableArray *) arrayName:(int) senderID;

BUT, here is the tricky part. The particular arrayName argument depends on what the senderID is. Specifically, each arrayName has a number at the end of it (i.e. array1, array2, etc.) that matches the senderID in this method. Is there a way to dynamically add in an integer to the end of array name as a parameter? Or an entirely different and better way to yield the same result?

In other words, what I want to create is this sort of a situation:

- (void) startBuildingXArray: (NSMutableArray *) arrayName+(senderID):(int) senderID;

Of course that is not in any way valid code, I'm just trying to demonstrate what I want to happen. Can anyone suggest any sort of solution?

Community
  • 1
  • 1
jac300
  • 5,182
  • 14
  • 54
  • 89
  • possible duplicate of [ObjC equivalent of PHP's "Variable Variables"](http://stackoverflow.com/questions/2283374/objective-c-equivalent-of-phps-variable-variables), [Create multiple variables based on an int count](http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count/), [Syntax help: variable as object name](http://stackoverflow.com/questions/7940809/syntax-help-variable-as-object-name) – jscs Oct 20 '12 at 19:48
  • 1
    if senderID is an argument then why do you also want it as part of the method name? – Jonathan. Oct 20 '12 at 21:07

1 Answers1

1

You're lucky: Objective-C is a dynamic language, so you can create selectors (method names) at runtime and also add corresponding implementation functions to them. Let's assume you have already implemented these methods (for example, from startBuildingXArray:arrayName1: to ...arrayName9: etc.), and you're looking for a way to call them depending on the integer ID:

- (void)callMethodWithParam:(NSMutableArray *)parm ID:(int)ident
{
    // get the selector name and the selector
    char zelektor[128];
    snprintf(zelektor, sizeof(zelektor), "startBuildingXArray:arrayName%d:", ident);
    SEL realSel = sel_getUid(zelektor);

    // Alternatively you can use Foundation as well:
    /*
    NSString *zelektor = [NSString stringWithFormat:@"startBuildingXArray:arrayName%d:", ident];
    SEL realSel = NSSelectorFromString(zelektor);
     */

    // Grab a function pointer to the implementation corresponding to the selector
    IMP imp = class_getInstanceMethod([self class], realSel);

    // and call the function pointer just obtained
    imp(self, realSel, parm, ident);
}

If you want to mass-create methods with names like this, you can use a similar approach but use the class_addMethod() Objective-C runtime function instead.

However, this is a hack. I'd rather suggest you use one function and implement its task depending on the integer identifier that is passed in.