使用performSelector时崩溃:从另一个类传递SEL

时间:2012-02-15 19:00:32

标签: objective-c cocoa-touch selector performselector

是否可以将选择器发送到另一个类并让它在另一个类上执行?

这似乎与错误*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[webManager _selector]: unrecognized selector sent to instance一起崩溃。如果无法做到这一点,您会建议什么作为替代方案?

方法按照执行顺序放置。

//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!");
}

2 个答案:

答案 0 :(得分:3)

这是你的问题:

[self performSelector:@selector(_selector)];

SEL是表示方法名称的类型。 @selector是一个编译器指令,它将括号内的文字文本转换为SEL

但是_selector,你的ivar,已经包含一个SEL。您正在将文本“_selector”转换为SEL,然后尝试使用它。由于目标类中不存在选择器“_selector”的方法,因此会出现异常。

将行更改为:

[self performSelector:_selector];

一切都应该是花花公子。这使用您已存储在变量 SEL中的_selector

另外,一般来说,请发布您的真实代码

答案 1 :(得分:3)

[self performSelector:@selector(_selector)];   

上面的代码实际上转换为[self _selector],我假设它不是你想要的。您应该将代码更改为

[self performSelector:_selector];