1 に答える
1
幸運なことに、Objective-C は動的言語であるため、実行時にセレクター (メソッド名) を作成し、対応する実装関数をそれらに追加することもできます。これらのメソッド (たとえば from startBuildingXArray:arrayName1:
to...arrayName9:
など) を既に実装しており、整数 ID に応じてそれらを呼び出す方法を探しているとします。
- (void)callMethodWithParam:(NSMutableArray *)parm ID:(int)ident
{
// get the selector name and the selector
char zelektor[128];
snprintf(zelektor, sizeof(zelektor), "startBuildingXArray:arrayName%d:", ident);
SEL realSel = sel_getUid(zelektor);
// Alternatively you can use Foundation as well:
/*
NSString *zelektor = [NSString stringWithFormat:@"startBuildingXArray:arrayName%d:", ident];
SEL realSel = NSSelectorFromString(zelektor);
*/
// Grab a function pointer to the implementation corresponding to the selector
IMP imp = class_getInstanceMethod([self class], realSel);
// and call the function pointer just obtained
imp(self, realSel, parm, ident);
}
このような名前のメソッドを大量に作成する場合は、同様のアプローチを使用できますが、代わりにclass_addMethod()
Objective-C ランタイム関数を使用できます。
ただし、これはハックです。1 つの関数を使用し、渡された整数識別子に応じてそのタスクを実装することをお勧めします。
于 2012-10-20T19:55:52.447 に答える