NSURLConnection的initWithRequest何时返回nil [英] When does NSURLConnection's initWithRequest return nil
问题描述
有谁知道在初始化 NSURLConnection
的情况下,返回nil而不是创建的连接。文档说它可能但是没有指定何时发生。
Does anyone know in which situations initializing a NSURLConnection
returns nil instead of the created connection. The documentation says it's possible but fails to specify when this happens.
有问题的方法/消息:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-
根据 NSURLConnection
类参考:
返回值:URL请求的URL连接。如果无法初始化连接,则返回nil。
Return Value: The URL connection for the URL request. Returns nil if a connection can't be initialized.
URL加载系统编程指南中说明如下:
The URL Loading System Programming Guide says the following:
如果NSURLConnection无法为请求创建连接,则initWithRequest:delegate:返回nil。
If NSURLConnection can’t create a connection for the request, initWithRequest:delegate: returns nil.
-
虽然此方法可能返回nil,但我无法想出触发此方法的方案。我尝试了以下方案:
While it's possible that this method returns nil, I'm unable to come up with a scenario which triggers this. I've tried the following scenarios:
-
URLRequest
带有空网址:connection:didFailWithError:
使用不支持的URL作为错误调用委托方法。 -
URLRequest
包含无效的url:connection:didFailWithError:
调用委托方法时出现bad URL错误。 -
URLRequest
,且不存在url:connection:didFailWithError:
调用委托方法时出现找不到指定主机名的服务器。错误。 - 有效请求但没有互联网:
连接:didFailWithError:
调用委托方法时Internet连接似乎处于脱机状态。错误。 - 无请求:导致崩溃。
URLRequest
with an empty url:connection:didFailWithError:
delegate method is called with "unsupported URL" as error.URLRequest
with invalid url:connection:didFailWithError:
delegate method is called with "bad URL" as error.URLRequest
with nonexistent url:connection:didFailWithError:
delegate method is called with "A server with the specified hostname could not be found." as error.- Valid request but no internet:
connection:didFailWithError:
delegate method is called with "The Internet connection appears to be offline." as error. - nil request: causes a crash.
initWithRequest
方法在每个场景中返回一个有效的 NSURLConnection
(除了最后一个场景)并调用连接:didFailWithError:
有适当的错误。
The initWithRequest
method returned a valid NSURLConnection
in each scenario (besides the last one) and called the connection:didFailWithError:
with an appropriate error.
有没有人能够找出导致nil返回的场景?
Has anybody been able to figure out which scenario does cause nil to be returned?
推荐答案
我猜答案是从不。似乎NSURLConnection返回nil的唯一方法是在[super init]失败。 ([super init]返回nil)但是作为NSURLConnection的超类是NSObject和NSObjects init只返回self(从不为零)
I guess the answer is "Never". Seems only way for NSURLConnection to return nil is failing at [super init]. ([super init] returning nil) But as super class of NSURLConnection is NSObject and NSObjects init just returns self (never nil)
PS:这是IOS SDK 4.0,模拟器,可以在设备上有所不同。
PS: That's for IOS SDK 4.0, on emulator, can be different on device.
这篇关于NSURLConnection的initWithRequest何时返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!