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)];   

上記のコードは実際には [self _selector] に変換されますが、これはあなたが望むものではないと思います。コードを次のように変更する必要があります

[self performSelector:_selector];   
于 2012-02-15T19:58:36.283 に答える
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 に答える