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!
Apurv
Use this instead:
[self performSelector:NSSelectorFromString(methodName)]
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