【问题标题】:NSURLConnection sendSynchronousRequest with ARCNSURLConnection sendSynchronousRequest 与 ARC
【发布时间】:2012-01-03 16:42:02
【问题描述】:

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

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

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

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

错误

Objective-C 指针到 'NSURLResponse 的隐式转换 *__autoreleasing *' 不允许使用 ARC

Objective-C 指针到 'NSError 的隐式转换 *__autoreleasing *' 不允许使用 ARC

file://localhost/Users/jason/Projects/test/Data/DataService.m:错误: 自动引用计数问题:隐式转换 Objective-C 指向 'NSURLResponse *__autoreleasing *' 的指针是 ARC不允许

file://localhost/Users/jason/Projects/test/Data/DataService.m:错误: 自动引用计数问题:隐式转换 不允许使用指向“NSError *__autoreleasing *”的 Objective-C 指针 圆弧

警告

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

不兼容的指针类型将“NSError *_strong”发送到参数 输入 'NSError *_autoreleasing *'

据我所知,引用传递是什么搞砸了,但我不确定解决这个问题的正确方法是什么。有没有“更好”的方式来完成与 ARC 类似的任务?

【问题讨论】:

    标签: objective-c nsurlconnection automatic-ref-counting


    【解决方案1】:
      NSError *error = nil;
      NSHTTPURLResponse *responseCode = nil;
    
      NSURLRequest *request;
    
      NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
    

    您缺少对错误/响应代码指针的引用!

    【讨论】:

    • LOL...让我在假期后思考!
    【解决方案2】:

    你必须使用 (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
    }
    

    否则,您不能将响应和错误用作全局变量。如果这样做,它们将无法正常工作。如下所示:

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

    上面的代码不起作用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多