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?

2
  • What are you actually trying to accomplish as an end game? Calling different functions depending on string values, or calling a function by name? Commented Jun 9, 2013 at 1:07
  • calling different functions depending on string values... Commented Jun 9, 2013 at 1:33

1 Answer 1

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.

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

3 Comments

Thanks - I guess I was just dreaming there for a minute.
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.
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.

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.