使用performSelector时发生崩溃:使用从另一个类传递的SEL [英] Crash when using performSelector: with a SEL passed from another class
问题描述
是否可以向另一个类发送一个选择器,并在另一个类上执行?
Is it possible to send a selector to another class and have it perform on that other class?
这似乎与错误 ***由于未捕获异常NSInvalidArgumentException终止应用程序,原因:' - [webManager _selector]:无法识别的选择器发送到实例
。如果这是不可能的,你会推荐什么作为替代?
This seems to crash with the error *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[webManager _selector]: unrecognized selector sent to instance
. If this is not possible, what would you recommend as an alternative?
方法是按照它们执行的顺序放置。
The methods are placed in the order that they are performed.
//in HomeViewController
-(void)viewDidLoad
{
WebManager *webManager = [[WebManager alloc] init];
URLCreator *urlCreator = [[URLCreator alloc] initWithParam:@"default"];
[webManager load:[urlCreator createURL] withSelector:@selector(testSelector)];
}
//in WebManager, which is also the delegate for the URL it loads when the load method is called...
-(void)load:(NSString*)url withSelector:(SEL)selector
{
_selector = selector;
[self load:url];
}
-(void)load:(NSString*)url{
NSURLRequest * request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
//now the delegate response, ALSO in WebManager
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Connection did finish loading. Parsing the JSON");
[self getJSONDict:rawData]; //parses the data to a dictionary
//perform the selector that is requested if there is one included
if (_selector)
{
NSLog(@"Performing selector: %@", NSStringFromSelector(_selector));
//the selector is called testSelector
[self performSelector:@selector(_selector)];
}
}
- (void)testSelector //also in the WebManager class
{
NSLog(@"Selector worked!");
}
推荐答案
/ p>
This is your problem:
[self performSelector:@selector(_selector)];
A SEL
的方法。 @selector
是一个编译器指令,它将括号内的文本文本转换为 SEL
。
A SEL
is a type representing the name of a method. @selector
is a compiler directive which converts the literal text inside the brackets into a SEL
.
但是 _selector
,您的ivar已经包含 SEL
。您正在将文本_selector转换为 SEL
,然后尝试使用它。因为在目标类中没有使用选择器_selector的方法,所以会出现异常。
But _selector
, your ivar, already contains a SEL
. You're converting the text "_selector" into a SEL
, and then trying to use that. Since no method with the selector "_selector" exists in the target class, you get an exception.
将行更改为:
[self performSelector:_selector];
,一切都应该dandy。这使用已经存储在变量 _selector
中的 SEL
。
and everything should be dandy. This uses the SEL
which you already have stored in the variable _selector
.
此外,一般来说,请先张贴您的实际代码。
这篇关于使用performSelector时发生崩溃:使用从另一个类传递的SEL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!