0

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

这似乎因错误而崩溃*** 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!");
}
4

2 回答 2

3

这是你的问题:

[self performSelector:@selector(_selector)];

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

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

将行更改为:

[self performSelector:_selector];

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

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

于 2012-02-15T19:57:11.680 回答
3
[self performSelector:@selector(_selector)];   

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

[self performSelector:_selector];   
于 2012-02-15T19:58:36.283 回答