3

嗨,我正在尝试制作一个以选择器为参数的 Objective-C 方法。但我不断收到“发送到实例的无法识别的选择器”错误消息。我正在执行以下操作:

这是带有选择器参数的方法:

-(void)createURL: (SEL) selector{ 
dispatch_sync(kBgQueue,^{
NSData* data = [NSData dataWithContentsOfURL: wcfURL];
    [self performSelectorOnMainThread:@selector(selector)
                           withObject:data waitUntilDone:YES];


});
}

这是我想成为选择器的方法:

-(void)fetchedUserType:(NSData *)responseData{

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions
                                                       error:&error];

userType = [json objectForKey:@"getUserTypeResult"];
}

这就是我调用我的方法的地方:

- (void)viewDidLoad
{
[super viewDidLoad];
NSString *url = [NSString stringWithFormat:@"http://10.211.55.3:1234/Service1.svc/getUserType/%@", userEmail];
wcfURL = [[NSURL alloc]initWithString:url];
SEL sel = NSSelectorFromString(@"fetchedUserType:");
[self createURL:sel];

}

4

1 回答 1

4

编辑1:

你的错误在这里:

 [self performSelectorOnMainThread:@selector(selector)
 ----------------------------------^^^^^^^^^^^^^^^^^^^

selector已经是一个选择器,而您又将其放入@selector() 中。

它应该是

 [self performSelectorOnMainThread:selector withObject:data waitUntilDone:YES];

编辑0:

你的代码是正确的。只有当您的 SEL 方法在当前类中找不到时,您才会收到错误消息。

如下面的代码所示,如​​果我将方法名称sum更改add为此将引发相同的错误。

-(void)sum{
    NSLog(@"sum");
}

-(void) createURL: (SEL) selector{
    [self performSelector:selector];
}

- (IBAction)total:(id)sender {
    SEL sel = NSSelectorFromString(@"sum");
    [self createURL:sel];
}

此外,您还需要满足方法签名。如果您的方法采用一个参数,则您需要发送一个。

-(void)sum:(id)integer{
    NSLog(@"sum:%ld",[integer integerValue]);
}

-(void) createURL: (SEL) selector{
    //NSData* data = [NSData dataWithContentsOfURL: nil];
    //[self performSelectorOnMainThread:@selector(selector) withObject:data waitUntilDone:YES];

    [self performSelector:selector withObject:@(12)];
}

- (IBAction)total:(id)sender {
    NSInteger total=0;

    for (id element in self.arrayController.arrangedObjects) {
        total += [element firstNumber]*[element secondNumber];
    }
    [self.label setStringValue:[NSString stringWithFormat:@"%ld",total]];


    SEL sel = NSSelectorFromString(@"sum:");
    [self createURL:sel];

}
于 2013-03-11T17:11:54.703 回答