Jun. 26th, 2012

bcholmes: (beret)

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.

Mirrored from Under the Beret.

Profile

bcholmes: (Default)
BC Holmes

February 2025

S M T W T F S
      1
2345678
9101112131415
16171819202122
2324252627 28 

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Powered by Dreamwidth Studios