1

有一个要求,我需要从其他类调用方法,但是方法名称会随着不同的动作而改变,如下所示:

NSArray *arrays = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];
for ( NSString *array in arrays ){
blablabla.......
Aclass *abc = [[Aclass alloc] methodName%@:variable],array;
blablabla.......
}

有没有办法在 Objective-C 中编写类似的代码?

谢谢!

更多信息:Aclass 中的方法名称如下:

-(NSArray *)procWithAAA:(NSInteger)aaaID

谢谢!

Aclass 中的方法名称如下:

-(NSArray *)procWithAAA:(NSInteger)aaaID

---------根据你们的建议,我编写如下代码,但它不起作用--------

NSArray *arrays = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];
for ( NSString *array in arrays ){

SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"procWith%@", array]);

if ([Sync respondsToSelector:customSelector]) {
                        Aclass * abc = [Aclass performSelector:customSelector:aaaID];
                    }else {
                        NSLog(@"## Class does not respond to %@", customSelector);
                    }

Aclass * abc = [Aclass performSelector:customSelector:aaaID]; 这部分在 Objective-C 中是不允许的。

谢谢

4

3 回答 3

1

您可以使用[self performSelector:<#(SEL)#> withObject:<#(id)#>];

 NSArray *selectorArray = [NSArray arrayWithObjects:@"abc",@"gcd", nil];

for (NSString *method in selectorArray) 
{
     [self performSelector:NSSelectorFromString(method) withObject:nil];
}

带参数的方法,

NSArray *selectorArray = [NSArray arrayWithObjects:@"abc:",@"gcd:", nil];

for (NSString *method in selectorArray) 
{
     [self performSelector:NSSelectorFromString(method) withObject:@"test"];
}
于 2012-04-09T06:03:48.793 回答
1

用于NSSelectorFromString将字符串转换为SEL, 然后-[NSObject performSelector:]NSInvocation调用方法。

或者,如果可以的话,使用键值编码

于 2012-04-09T06:04:31.007 回答
0

您可以使用该NSSelectorFromString功能。

SEL customSelector = NSSelectorFromString(@"selectorName");
if ([class respondsToSelector:customSelector]) {
    [class performSelector:customSelector];
}
else {
    NSLog(@"## Class %@ does not respond to %@", class, customSelector);
}

有关选择器的更多信息可以在文档中找到。

于 2012-04-09T06:04:13.073 回答