Tag Archive for cocoa

Objective-C Oddities

I was tweaking a bit of Objective-C code the other day, and stumbled upon one of those situations that seemed like it should be straight-forward, but which bit me. Consider the following.

My app is downloading some information in a background thread. Here’s my code:

NSData *data = [NSURLConnection sendSynchronousRequest:request 
                   returningResponse:&response error:error];
if (error != nil) {
    NSLog(@"error : %@", error.localizedDescription);
} else {
    
    // check response code, etc.
    ...
}  

The code compiled fine, but when I ran it, I would sometimes get an EXC_BAD_ACCESS crash. Turns out, the Cocoa APIs are designed to communicate information via the response type, as StackOverflow clarified for me. According to the Apple Error Handling standards:

you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

So I’d needed to write:

NSData *data = [NSURLConnection sendSynchronousRequest:request 
                   returningResponse:&response error:error];
if (data != nil) {
    // check response code, etc.
    ...
} else if (error != nil) {
    NSLog(@"error : %@", error.localizedDescription);
}  

At some level, this type of error feels wrong. I’ve got a non-nil error object; it’s just in a state that I can’t use it. It feels to me like there’s something messed up with the way the API works.

But whatever. Data first; error second.