سؤال

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!

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top