Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
What are you actually trying to accomplish as an end game? Calling different functions depending on string values, or calling a function by name? – Joachim Isaksson yesterday
calling different functions depending on string values... – ObjectiveFlash yesterday

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
Thanks - I guess I was just dreaming there for a minute. – ObjectiveFlash yesterday
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. – ObjectiveFlash yesterday
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 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.