iOS中的回调函数使用performSelector

时间:2014-08-19 10:16:54

标签: ios objective-c callback

我正在尝试创建一个在iOS中调用被调用者的回调函数的方法。在浏览动态函数调用之后,这是我尝试的: -

部首: -

+(void)url:(NSString *)url handler:(NSObject *)handler callback:(NSString *)callbackfn;

实现: -

+(void)url:(NSString *)url handler:(NSObject *)handler callback:(NSString *)callbackfn{
NSURLRequest *imageLoader = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

[NSURLConnection sendAsynchronousRequest:imageLoader queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    SEL s = NSSelectorFromString(callbackfn);
    if ([handler respondsToSelector:s]) {
        [handler performSelector:s];
    }else{
        NSLog(@"does not responds to handler %@",[handler self]);
    }


}];

}

ViewController调用它: -

-(IBAction)loadImage:(id)sender{

NSString *url = @"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg";
[NetCall url:url handler:self callback:@"imageRec"];

}

-(void)imageRec{
    NSLog(@"net call done");
}

但是当代码执行时,它在LOG中打印“不响应处理程序”。 我是否以错误的方式传递函数名称?

日志: -

2014-08-19 17:54:58.419 Testing[2194:78586] does not responds to handler <ViewController: 0x7b16c390>

1 个答案:

答案 0 :(得分:1)

如果您尝试从异步请求获取回调,我建议您使用块语法。它适用于iOS4 +。

+ (void)url:(NSString *)url callback:(void (^)(NSData *data))callback {
    NSURLRequest *imageLoader = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    [NSURLConnection sendAsynchronousRequest:imageLoader queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        if (callback)
            callback(data);
    }];
}

这就是你怎么称呼它:

// __weak typeof(self) weakSelf = self;  
NSString *stringUrl = @"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg";  
[MyViewController stringUrl callback:^(NSData *data) {

    // Do something here with *data*
    // __strong typeof(weakSelf) strongSelf = weakSelf;
}];

如果您需要使用self,请使用弱引用,否则可能会保留强引用,并可能导致问题。 为了帮助您构建块,有这个网站http://goshdarnblocksyntax.com/


如果你仍然想使用选择器技术,这里是修改后的代码:

+ (void)url:(NSString *)url handler:(NSObject *)handler selector:(SEL)selector {
    NSURLRequest *imageLoader = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    [NSURLConnection sendAsynchronousRequest:imageLoader queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if ([handler respondsToSelector:selector]) {
            [handler performSelector:selector];
        }else{
            NSLog(@"does not responds to handler %@", handler);
        }

    }];
}

在你的ViewController中:

- (IBAction)loadImage:(id)sender {

    NSString *url = @"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg";
    [NetCall url:url handler:self selector:@selector(imageRec)];
}

- (void)imageRec {
    NSLog(@"net call done");
}
相关问题