2012-01-03 32 views
10

Tôi bắt đầu chơi với ARC và một trong những trải nghiệm đầu tiên tôi đang cố gắng thực hiện cuộc gọi HTTP tới một URL và lấy lại một số dữ liệu. Tất nhiên, các mã trạng thái HTTP là quan trọng với tôi, vì vậy có nghĩa là tôi đi đến tôi "goto" của việc sử dụng sendSynchronousRequest như:NSURLConnection sendSynchronousRequest với ARC

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

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

Với ARC cho phép tôi nhận được một lỗi biên dịch và cảnh báo trên rằng dòng cuối cùng.

lỗi:

Implicit conversion of an Objective-C pointer to 'NSURLResponse *__autoreleasing *' is disallowed with ARC

Implicit conversion of an Objective-C pointer to 'NSError *__autoreleasing *' is disallowed with ARC

file://localhost/Users/jason/Projects/test/Data/DataService.m: error: Automatic Reference Counting Issue: Implicit conversion of an Objective-C pointer to 'NSURLResponse *__autoreleasing *' is disallowed with ARC

file://localhost/Users/jason/Projects/test/Data/DataService.m: error: Automatic Reference Counting Issue: Implicit conversion of an Objective-C pointer to 'NSError *__autoreleasing *' is disallowed with ARC

Warnings:

Incompatible pointer types sending 'NSHTTPURLResponse *_strong' to parameter of type 'NSURLResponse *_autoreleasing *'

Incompatible pointer types sending 'NSError *_strong' to parameter of type 'NSError *_autoreleasing *'

Từ những gì tôi có thể nói việc thông qua tham chiếu là những gì đang rối tung này lên, nhưng tôi không chắc chắn những gì cách chính xác để giải quyết vấn đề này. Có cách nào "tốt hơn" để thực hiện nhiệm vụ tương tự với ARC không?

Trả lời

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

    NSURLRequest *request; 

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

bạn thiếu tham chiếu đến con trỏ lỗi/responceCode!

+0

LOL ... phục vụ tôi để cố nghĩ sau những ngày nghỉ! –

2

Bạn phải sử dụng loại (NSHTTPURLResponse __autoreleasing *) và loại (NSError __autoreleasing *).

NSHTTPURLResponse __autoreleasing *response = nil; 
NSError __autoreleasing *error = nil; 

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

Và bạn có thể xử lý chúng trong sau:

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

Nếu không, bạn không thể phản ứng sử dụng và lỗi như vars toàn cầu. Nếu có, chúng sẽ không hoạt động chính xác.Làm như sau:

.h 
NSHTTPURLResponse *__autoreleasing *response; 
NSError *__autoreleasing *error; 

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

Mã trên sẽ không hoạt động!