Safe Casting, but EXC_BAD_ACCESS anyway

176 views Asked by At

Disclaimer: I'm quite new to Obj-C and iOS (5, ARC enabled).

The following implementation of an NSURLConnectionDelegate method creates EXC_BAD_ACCESS in the NSLog call inside the if:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    NSLog(@"Response %@", response );
    if([response isKindOfClass:[NSHTTPURLResponse class]])
    {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
        NSLog(@"HTTP status code %@", [httpResponse statusCode]);
    }
}

As far as I managed to find out, the EXC_BAD_ACCESS is caused mostly due to allocation issues, wrong casting, and bad memory management. None of that applies here (I hope).

Thanks in advance, Chris

Solution: Noobie error in formatting the og string. Change the second NSLog to:

NSLog(@"HTTP status code %i", [httpResponse statusCode]);
1

There are 1 answers

0
justin On BEST ANSWER

statusCode returns an NSInteger (a long or an int), not a pointer to an NSObject instance.

The format specifier %@ is used for NSObjects arguments. The problem likely occurs when the integer value that is returned from statusCode is interpreted/passed as a pointer to an object and then messaged or otherwise treated as a pointer to an object by the runtime. When an object argument is printed via %@ the logger uses the result of the object's -[NSObject description].

You can avoid this problem in the future by turning up your compiler warnings and correcting the issues it generates.