0

I have a situation in objective-c, specifically for iOS app development, that a particular method will execute and return a number, from 01 - 20. Also, I have 20 different methods, name m01, m02, m03, etc.

How can I program my code so that my first method calls another method that corresponds to the returned number from the first method?

Something like this:

[self m[NSStringWithFormat=@"%i", myOutputFromMethod1];

Can someone please help me get this to work?

jake9115
  • 3,644
  • 11
  • 41
  • 75

4 Answers4

5

You can get the name of a selector using NSSelectorFromString([NSString stringWithFormat:@"m%i", myOutputFromMethod1]) and then perform it using [self performSelector:].

borrrden
  • 32,544
  • 8
  • 70
  • 106
2
SEL s = NSSelectorFromString([NSString NSStringWithFormat:@"m%i", myOutputFromMethod1]);
[anObject performSelector:s];
Vinayak Kini
  • 2,919
  • 20
  • 35
2

Using dozens of methods depending upon a returning value is definitely not a good programming practice, (unless you have some very special requirements which I'm not aware of). You can call the same method but pass a paramter to it. That parameter can be put into a switch statement, then you can write a 'case' for each value of parameter. For example

-(void) method_m :(int)mNum
{
    switch(mNum)
    {
        case 0:
            //your code for method 00
            break;
        case 1:
            //your code for method 01
            break;
        default:
            break;
    }
}

I hope it helps.

Usman.3D
  • 1,753
  • 3
  • 16
  • 26
0
SEL s = NSSelectorFromString([NSString NSStringWithFormat: @"m%i", myOutputFromMethod1]);

if ([anObject respondsToSelector: s])
{
    [anObject performSelector: s];
}
stosha
  • 1,935
  • 2
  • 24
  • 26