0

I am trying to use an array of strings dynamically access methods at runtime within my class. For now the methods are already there, eventually I want to create them. Is this possible?

For example:

bool nextLevel=NO;
for(NSString * match in gameLevels)
{

    if([match isEqualToString:self.level])
    {
        nextLevel=YES;
    }
    else if(nextLevel==YES)
    {
        self.level=match;
        nextLevel=NO;
    }
}
//access method named self.level

Thank you in advance!

6
  • 2
    Your question is not clear, please elaborate more Commented May 13, 2014 at 18:09
  • @KhawarAli I think he wants to have it so he can do [self @"methodThatDoesSomething"] where the string comes from possible functuon names in an array Commented May 13, 2014 at 18:11
  • 2
    Are you saying the NSString contains the names of methods to call? Yes that's possible. Look at NSSelectorFromString Commented May 13, 2014 at 18:11
  • Apologies for the lack of clarity. Martin has it exactly. Commented May 13, 2014 at 18:13
  • There are several ways to call a method by name. See, eg, the Objective-C Runtime Reference. Creating a method is a bit (actually, a whole lot) more difficult. Commented May 13, 2014 at 18:13

2 Answers 2

1

I use:

NSSelectorFromString(selectorString)

In your case, the selectorString would be:

NSString * selectorString = @"setLevel:";

This is 'setLevel' instead of 'level' because the Objective-C runtime will automatically expand dot properties to these selector names when assignment occurs.

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

2 Comments

you mean setLevel:?
Why yes I do. Good catch. The colon is necessary because we are passing a parameter.
0

To access a method based on a string, check the other answer.

To add a method in the runtime you need to create a IMP function or block.

If using a function, could be something like:

void myMethodIMP(id self, SEL _cmd)
{
    // implementation ....
}

You could also use a block like this:

IMP blockImplementation=imp_implementationWithBlock(^(id _self, ...){
    //Your Code here
}

Then you need to add the method, like this:

class_addMethod(yourClass, @selector(selectorName), (IMP) blockImplementation, encoding);

The encoding part is a special runtime encoding to describe the type of parameters your method receives. You can find that on the Objective-C runtime reference.

If you receive dynamic arguments on your generated methods, you need to use the va_list to read the values.

Comments

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.