ARC下的NSURLConnection sendSynchronousRequest

12

我开始尝试使用ARC,其中一个最早的实验是调用URL并获取一些数据。当然,对我来说HTTP状态码很重要,这意味着我使用了我的“惯用方式”,使用sendSynchronousRequest,如下所示:

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: error: Automatic Reference Counting Issue: 隐式转换 Objective-C 指针为“NSURLResponse *__autoreleasing *”使用 ARC 是不允许的。 file://localhost/Users/jason/Projects/test/Data/DataService.m: error: Automatic Reference Counting Issue: 隐式转换 Objective-C 指针为“NSError *__autoreleasing *”使用 ARC 是不允许的。
警告: 不兼容的指针类型发送 'NSHTTPURLResponse *_strong' 给类型为 'NSURLResponse *_autoreleasing *' 的参数。 不兼容的指针类型发送 'NSError *_strong' 给类型为 'NSError *_autoreleasing *' 的参数。
据我所知,引用传递是导致问题的原因,但我不确定解决此问题的正确方法。是否有一种使用ARC实现类似任务的“更好”的方法?
2个回答

24
  NSError *error = nil;
  NSHTTPURLResponse *responseCode = nil;

  NSURLRequest *request;

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

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


哈哈...假期后再思考真是太难了! - Jason Whitehorn

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
}

否则,你不能将response和error作为全局变量使用。如果这样做,它们将无法正常工作。例如下面的代码:
.h
NSHTTPURLResponse *__autoreleasing *response;
NSError *__autoreleasing *error;

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

上面的代码无法正常工作!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接