Objective C calling method dynamically with a string

后端 未结 2 1617
遥遥无期
遥遥无期 2020-12-01 01:50

Im just wondering whether there is a way to call a method where i build the name of the method on the fly with a string.

e.g. I have a method called loaddata

相关标签:
2条回答
  • 2020-12-01 02:25

    You can use the objc_msgSend function. It takes two parameters, the receiver and the selector to send to it:

    objc_msgSend(self, someSelector);
    

    You'll need to turn your string into the appropriate selector using NSSelectorFromString:

    NSString *message = [self getSomeSelectorName];
    objc_msgSend(self, message);
    

    The method also takes a variable number of arguments, so you can send messages with any number of arguments.

    NSString *message = [self getSomeSelectorNameWithManyArguments];
    objc_msgSend(self, message, arg1, arg2, arg3, arg4);
    
    0 讨论(0)
  • 2020-12-01 02:30

    You can try something like

    SEL s = NSSelectorFromString(selectorName);
    [anObject performSelector:s];
    
    0 讨论(0)
提交回复
热议问题