19

I've seen a lot of code, including Apple's SimpleURLConnections sample, that simply cast any NSURLResponse to a NSHTTPURLResponse. If it is always a NSHTTPURLResponse why do the NSURLConnections not return NSHTTPURLResponse?

I'm worried that if I simply downcast the response, I'm introducing buggy code.

For instance, is it OK to do this without checking isKindOfClass?

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
{
 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)redirectResponse;
 // do stuff
}
CornPuff
  • 1,924
  • 20
  • 24

2 Answers2

21

The safer way to do it is with introspection.

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)redirectResponse;
   // do stuff
}
mgold
  • 6,189
  • 4
  • 39
  • 41
20

It is ok if you are sure that your connection runs via HTTP protocol:

An NSHTTPURLResponse object represents a response to an HTTP URL load request. It’s a subclass of NSURLResponse that provides methods for accessing information specific to HTTP protocol responses.

If you are connecting via FTP, for example, then casting NSURLResponse to NSHTTPURLResponse will be incorrect.

Nekto
  • 17,837
  • 1
  • 55
  • 65
  • HTTP response codes must be 3 digits long, if you are getting more than that length, is not a valid HTTP response code. – Praveen-K Sep 13 '11 at 05:14
  • I suggest to do a better type-checking than just a cast, I have many cases of crashes related to NSURLResponse NOT being an NSHTTPURLResponse even though I'm only dealing with HTTP connections. – Psycho May 07 '12 at 14:16