首页 文章

使用ARC进行NSURLConnection sendSynchronousRequest

提问于
浏览
10

我开始玩ARC了,我尝试的第一个体验之一是对URL进行HTTP调用并获取一些数据 . 当然,HTTP状态代码对我来说很重要,所以这意味着我去了"goto"使用 sendSynchronousRequest ,如:

NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:responseCode error:error];

启用ARC后,我在最后一行收到编译器错误和警告 .

Errors

不允许将Objective-C指针隐式转换为'NSURLResponse * __ autoreleasing *'使用ARC文件隐式转换Objective-C指针为'NSError * __ autoreleasing *'不允许使用ARC文件:// localhost / Users / jason / Projects /test/Data/DataService.m:error:自动引用计数问题:ARC文件不允许将Objective-C指针隐式转换为'NSURLResponse * __ autoreleasing *':// localhost / Users / jason / Projects / test / Data /DataService.m:error:自动引用计数问题:ARC不允许将Objective-C指针隐式转换为'NSError * __ autoreleasing *'

Warnings

不兼容的指针类型将'NSHTTPURLResponse * _strong'发送到'NSURLResponse * _autoreleasing *'类型的参数不兼容的指针类型将'NSError * _strong'发送到'NSError * _autoreleasing *'类型的参数

从我可以告诉参考传递是什么搞乱了这一点,但我不确定解决这个问题的正确方法是什么 . 是否有一种“更好”的方式来完成ARC的类似任务?

2 回答

  • 2
    NSError *error = nil;
      NSHTTPURLResponse *responseCode = nil;
    
      NSURLRequest *request;
    
      NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
    

    你错过了对error / responceCode指针的引用!

  • 22

    您必须使用(NSHTTPURLResponse __autoreleasing *)类型和(NSError __autoreleasing *)类型 .

    NSHTTPURLResponse __autoreleasing *response = nil;
    NSError __autoreleasing *error = nil;
    
    // request
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    

    你可以在下面处理它们:

    if (response){
        // code to handle with the response
    }
    if (error){
        // code to handle with the error
    }
    

    否则,您 cannot 将响应和错误用作全局变量 . 如果有,他们将无法正常工作 . 如下所示:

    .h
    NSHTTPURLResponse *__autoreleasing *response;
    NSError *__autoreleasing *error;
    
    .m
    // request
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:response error:error];
    

    上面的代码 will not work!

相关问题