2

好吧,我正在创建一个自定义 SEL,例如:

NSArray *tableArray = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];
for ( NSString *table in tableArray ){
    SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@", table]);
    [self performSelector:customSelector withObject:0];
}

我收到一个错误: 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[Sync aaaWithaaa]:无法识别的选择器已发送到实例

但如果我用真实的方法名运行它,它就可以工作!

[self performSelector:@selector(aaaWithaaa:) withObject:0];

如何解决?

4

4 回答 4

6

您已经从字符串创建了选择器 - 将其传递给 performSelector: 方法:

[self performSelector:customSelector withObject:0];

编辑:请注意,如果您的方法采用参数,那么在从中创建选择器时必须使用冒号:

// Note that you may need colon here:
[NSString stringWithFormat:@"abcWith%@:", table]
于 2012-04-09T13:23:15.453 回答
1
NSArray *tableArray = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];

for ( NSString *table in tableArray ){
     SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@:", table]);
     [self performSelector:customSelector withObject:0];
 }
于 2012-04-09T13:25:06.237 回答
0

关闭。

不同之处在于@selector(aaaWithaaa:)您传递的是方法名称,但@selector(customSelector:)传递的是 SEL 类型的变量(带有备用冒号)。

相反,您只需要:

[self performSelector:customSelector withObject:0];

另一个区别是你在结尾处stringWithFormat:了一个冒号,但你没有。这一点很重要; 这意味着该方法需要一个参数。如果你的方法有一个参数,它需要在那里,即

[NSString stringWithFormat:@"abcWith%@:", table]
于 2012-04-09T13:24:54.483 回答
0
- (id)performSelector:(SEL)aSelector withObject:(id)anObject

第一个参数是SEL类型。

SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@", table]);
[self performSelector:customSelector withObject:0];
于 2012-04-09T13:26:18.183 回答