如何使用selector参数创建方法

时间:2013-03-11 17:02:09

标签: objective-c parameter-passing selector

您好我正在尝试制作一个具有选择器作为参数的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];

}

1 个答案:

答案 0 :(得分:3)

编辑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];

}