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,964
  • 12
  • 49
  • 78

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
  • 33,256
  • 8
  • 74
  • 109
  • Be aware, though, that the method *must* return an objective-c object (i.e. `NSNumber` as opposed to `int`) – borrrden Jun 13 '13 at 05:02
  • See my updated answer, you just insert what you were trying to create in your question. – borrrden Jun 13 '13 at 05:03
  • Awesome! A bit off topic, instead of [self method], how can I call a method from another .h/.m file? Would I need to import something? – jake9115 Jun 13 '13 at 05:05
  • Oh, it can also return `void` just to be clear, but if it does return it has to return an object. – borrrden Jun 13 '13 at 05:05
  • You can use `performSelector:` on *any* valid objective-c object that inherits from `NSObject` (which is virtually everything). – borrrden Jun 13 '13 at 05:06
  • Awesome! It is working great, but I received a warning: "PerformSelector may cause a leak because its selector is unknown". Is this something to worry about? Also, will Appel reject apps that have warnings? – jake9115 Jun 13 '13 at 05:38
  • http://stackoverflow.com/a/7017537/1155387 – borrrden Jun 13 '13 at 05:59
2
SEL s = NSSelectorFromString([NSString NSStringWithFormat:@"m%i", myOutputFromMethod1]);
[anObject performSelector:s];
Vinayak Kini
  • 2,919
  • 21
  • 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,791
  • 3
  • 16
  • 27
0
SEL s = NSSelectorFromString([NSString NSStringWithFormat: @"m%i", myOutputFromMethod1]);

if ([anObject respondsToSelector: s])
{
    [anObject performSelector: s];
}
stosha
  • 2,108
  • 2
  • 27
  • 29