12

I am beginning to play around with ARC, and one of the first experiements I was trying was to make an HTTP call to a URL and get back some data. Of course, the HTTP status code is important to me, so that means I went to my "goto" of using sendSynchronousRequest like:

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

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

With ARC enabled I get a compiler errors and warnings on that last line.

Errors:

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 *'

From what I can tell the reference passing is what is messing this up, but I am unsure what the correct way to resolve this is. Is there a "better" way to accomplish a similar task with ARC?

Rayfleck
  • 12,116
  • 8
  • 48
  • 74
Jason Whitehorn
  • 13,585
  • 9
  • 54
  • 68

2 Answers2

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

  NSURLRequest *request;

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

you missing the reference to the error/responceCode pointer!

CarlJ
  • 9,461
  • 3
  • 33
  • 47
2

You have to use the (NSHTTPURLResponse __autoreleasing *)type and (NSError __autoreleasing *)type.

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

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

And you can handle them in the follow:

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

Otherwise, you cannot use response and error as global vars. If did, they will not work correctly.Like following:

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

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

The code above will not work!