When is a NSURLResponse not a NSHTTPURLResponse?

人盡茶涼 提交于 2019-12-04 17:24:42

问题


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
}

回答1:


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.




回答2:


The safer way to do it is with introspection.

if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
   NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)redirectResponse;
   // do stuff
}


来源:https://stackoverflow.com/questions/7396966/when-is-a-nsurlresponse-not-a-nshttpurlresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!