好吧,我正在创建一个自定义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'而终止应用,原因:' - [同步aaaWithaaa]:无法识别的选择器发送到实例
但如果我使用真正的方法名称运行它就可以了!
[self performSelector:@selector(aaaWithaaa:) withObject:0];
如何解决?
答案 0 :(得分:6)
您已经从string创建了选择器 - 将其传递给performSelector:method:
[self performSelector:customSelector withObject:0];
修改:请注意,如果您的方法需要参数,则必须在从中创建选择器时使用冒号:
// Note that you may need colon here:
[NSString stringWithFormat:@"abcWith%@:", table]
答案 1 :(得分: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];
}
答案 2 :(得分:0)
关闭。
不同之处在于,使用@selector(aaaWithaaa:)
传递方法名称,但使用@selector(customSelector:)
传递SEL类型的变量(带有备用冒号)。
相反,你只需要:
[self performSelector:customSelector withObject:0];
另一个不同之处在于,在最后用冒号编写字符串,但stringWithFormat:
没有。这一点很重要;这意味着该方法需要一个参数。如果你的方法有一个参数,它需要在那里,即
[NSString stringWithFormat:@"abcWith%@:", table]
答案 3 :(得分:0)
- (id)performSelector:(SEL)aSelector withObject:(id)anObject
第一个参数是SEL
类型。
SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@", table]);
[self performSelector:customSelector withObject:0];