A dynamic method name (Objective-C)

你说的曾经没有我的故事 提交于 2019-12-02 03:46:16

问题


I have several methods, like below:

- (void)methodA;
- (void)methodB;
- (void)methodC;

and they are used depending on some conditions.

Now I want to dynamically use them, and I tried this:

NSString *methodName;
if(_flag == A) methodName = @"methodA";
else if (_flag == b) methodName = @"methodB";
else methodName = @"methodC";

[self performSelector:@selector(methodName)];

but it seems wrong.

So how should I use a dynamic method name for a given receiver depending on different situations?

Thanks a lot!


回答1:


Use this instead:

[self performSelector:NSSelectorFromString(methodName)]



回答2:


why don't you do in this manner??

if(_flag == A)
     [self performSelector:@selector(methodA)];
else if (_flag == b) 
     [self performSelector:@selector(methodB)];
else 
     [self performSelector:@selector(methodC)];

As the @selector needs function to call and not NSString.



来源:https://stackoverflow.com/questions/9138717/a-dynamic-method-name-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!