0

Would it be in any way possible to use an NSString variable as a way of calling a function in XCode?

This is just an example. I have a function called [Settings getBest1] which gets the high score of level one and [Settings getBest2] to get the high score of level two and so on for several levels.

I have an integer value which is the level who's high score I would like to see. What is the best way of coding the app so that I can use this integer to call the right function? Is there no better way than:

switch(levelInt) {
   case 1: [Settings getBest1]; break;
   case 2: [Settings getBest2]; break;
   case 3: [Settings getBest3]; break;
   case 4: [Settings getBest4]; break;
...
}

I'd love to be able to do the impossible:

NSString *getBestString = [NSString stringWithFormat:@"getBest%i", levelInt];
[Settings getBestString];

But since that's impossible - is there some other way of accomplishing this idea?

RanLearns
  • 4,086
  • 5
  • 44
  • 81

1 Answers1

1

This is not impossible but should really be avoided. There is a similar question located at Objective C calling method dynamically with a string

The compiler will complain and using this method can cause issues. If for example the user manages to enter an invalid method name this will crash your application (this can also of course happen with poor application design)

The switch method that you have been using is a much better way of doing this.

Community
  • 1
  • 1
Peter
  • 773
  • 1
  • 7
  • 23
  • Thanks - I guess I was just dreaming there for a minute. – RanLearns Jun 09 '13 at 01:40
  • That NSSelectorFromString code in the question you linked to seems to only act on a variable as well, not sure that it would call to a function in another class and return a value. – RanLearns Jun 09 '13 at 01:41
  • 1
    An nsstring is made from the input (as per your code). The nsstring is then converted into a selector. The selector is passed to performSelector which calls the method with the name that matches the selector value. – Peter Jun 09 '13 at 10:54