嗨,我是目标 C 的新手,想知道是否有人可以帮助我解决这个问题。我有几种不同的方法,每种方法都需要 3 个输入值,通常使用
[self methodA:1 height:10 speed:3]
但是我想从plist中的字符串中读取方法名称,例如,如果字符串是methodB,我会得到
[self methodB:1 height:10 speed:3]
对于“方法C”
[self methodC:1 height:10 speed:3]
等等。
任何想法我可以如何做到这一点我尝试使用 NSSelectorFromString 将字符串定义为选择器
NSString *string = [plistA objectForKey:@"method"];
SEL select = NSSelectorFromString(string);
[self performSelector:select:c height:b speed:a];
然而,这没有任何帮助将不胜感激。已尝试以下解决方案,但无法在这里工作是我尝试过的。
所以只是回顾一下我有一些方法,比如
spawnEnemyA:2 withHeight:3 withSpeed:4
spawnEnemyB:3 withHeight:2 withSpeed:5
我想从 plist 文件中读取我想传递给这些方法的值以及方法类型。我的代码如下,//////////////////////////////////// /////////////////
//这些是我从 plist 中读取的值,我希望我的方法使用
int a = [[enemySettings objectForKey:@"speed"] intValue];
int b = [[enemySettings objectForKey:@"position"] intValue];
int c = [[enemySettings objectForKey:@"delay"] intValue];
// I Also read the method name from the plist and combine it into a single string
NSString *method = [enemySettings objectForKey:@"enemytype"];
NSString *label1 = @"spawn";
NSString *label2 = @":withHeight:withSpeed:";
NSString *combined = [NSString stringWithFormat:@"%@%@%@",label1, method,label2];
//Check that the string is correct get spawnEnemyA:withHeight:withSpeed:
CCLOG(@"%@",combined);
//This is the Invocation part
NSInvocation * invocation = [ NSInvocation new ];
[ invocation setSelector: NSSelectorFromString(combined)];
[ invocation setArgument: &c atIndex: 2 ];
[ invocation setArgument: &b atIndex: 3 ];
[ invocation setArgument: &a atIndex: 4 ];
[ invocation invokeWithTarget:self ];
[invocation release ];
///////////////////////////////////////// /////////////////
代码编译没有任何错误,但没有调用方法。有任何想法吗?干杯