我开始玩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 ARC不允许使用__ autoreleasing *'
将Objective-C指针隐式转换为'NSError ARC不允许使用__ autoreleasing *'
file://localhost/Users/jason/Projects/test/Data/DataService.m:错误: 自动引用计数问题:隐式转换 Objective-C指向'NSURLResponse * __ autoreleasing *'的指针是 不允许使用ARC
file://localhost/Users/jason/Projects/test/Data/DataService.m:错误: 自动引用计数问题:隐式转换 不允许使用Objective-C指向'NSError * __ autoreleasing *'的指针 ARC
警告:
将'NSHTTPURLResponse * _ strong'发送到的不兼容的指针类型 'NSURLResponse * _autoreleasing *'
类型的参数不兼容的指针类型将'NSError * _ strong'发送到参数 输入'NSError * _autoreleasing *'
据我所知,引用传递是弄乱这个问题的,但我不确定解决这个问题的正确方法是什么。是否有一种“更好”的方式来完成ARC的类似任务?
答案 0 :(得分:23)
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
NSURLRequest *request;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
你错过了对error / responceCode指针的引用!
答案 1 :(得分: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];
上面的代码无效!