I saw some code like this :
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if(connection) {
receivedData = [NSMutableData data];
} else {
}
How do I make it to go into the else? I tried disabling the connection and still never go into the else it goes through the didFailWithError … so wondering if it is even necessary??
The apple documentation on the return value of this method says:
This could be misleading for those not familiar with Cocoa (and Objective-C) best practices.
Generally an
initmethod should return an object; unless there is some fundamental reason returning an object would be dangerous. Most other languages handle cases like this by throwing exceptions, requiring you to add countless try/catch brackets.The
initWithRequest:delegate:method will returnnilif (for example) you pass anilas the request parameter; and for good reason. Why create a connection object to have no useful purpose?However lets consider a situation like airplane mode or an invalid url. If
initWithRequest:delegate:just returnednilthen how would you know what went wrong? Allowing the connection to callconnection:didFailWithError:gives you an opportunity to gain insight into the particular failing, through the error parameter.To address your question as to whether handling the event of the connection being
nilis ever necessary: It depends. If the connection fails to initialize it will never call the connection delegate methods, so if your code relies on these callbacks to issue subsequent requests then yes it’s necessary.A side note: Creating your
NSMutableDatahere is a little premature since you don’t yet know that there is a valid connection. An answer I gave here gave some very basic sample code regarding where to do this.