I'm kind of a newbie in objective-c and I'm having issues when I call a NSArray from other class. I have a class which handles the parsing of a XML feed and another to manage the UItableview stuff. It's weird because when it's done synchronously (using NSXMLParser methods) all data is shown in the table, but when I use the NSURLConnection to make it asynchronous it parses all the data but the array is empty when it's called. If I call NSLog it shows all data contained the newsStories array when the data is being parsed, but somehow its deleted when I call it.
On the parser class I have and all the methods of the NSXMLParser:
- (void)parseXMLFileAtUrl:(NSString *)URL {
data = [[NSMutableData alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
data = [[NSMutableData alloc]init];
}
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//Reset the data as this could be fired if a redirect or other response occurs
[data setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data
{
//Append the received data each time this is called
[data appendData:_data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Start the XML parser with the delegate pointing at the current object
_parser = [[NSXMLParser alloc] initWithData:data];
newsStories = [[NSMutableArray alloc] init];
[_parser setDelegate:self];
[_parser setShouldProcessNamespaces:NO];
[_parser setShouldReportNamespacePrefixes:NO];
[_parser setShouldResolveExternalEntities:NO];
[_parser parse];
}
And this is how I call the array:
-(BOOL) loadData{
NSString *latestUrl = [[NSString alloc] initWithString:feed];
if ([latestArray count] == 0) {
news = [[news_parser alloc]init];
[news parseXMLFileAtUrl:latestUrl];
[self setArray:news.newsStories];--- here it says null for Array and for newsItems
}
[latestUrl release];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
array = [[NSMutableArray alloc]init];
_News.rowHeight =85;
[self loadData];
[self._News reloadData];
}
Any help would be appreciated, thanks guys!
Regards.
... Do you understand what asynchronous means? It means that your function will return and the connection will continue, making the callbacks when it is ready. The way you have this coded up, you start the connection and then immediately try to use the data -- it isn't there yet! You need to wait until after connectionDidFinishLoading before you try to use the array.
Do some more research on what exactly it means to be asynchronous; it seems you're not understanding that.
Edit
Let me clarify, since you seem to have missed my point. Your viewDidLoad function finishes long before your connectionDidFinishLoading callback gets called, and so of course the newsStories array is not there yet. When you call:
[news parseXMLFileAtUrl:latestUrl];
in the loadData function, that doesn't stop and wait for the connection to return; if it were synchronous, it would, but asynchronous does not. (Hence I ask you to research what asynchronous actually means, which apparently you still have not done). Since that call returns and then you immediately try to use the loaded data (long before the connectionDidFinishLoading is called) you naturally don't have any data in there.
From Apple's docs:
Mutable objects are generally not thread-safe. To use mutable objects
in a threaded application, the application must synchronize access to
them using locks. (For more information, see “Atomic Operations”). In
general, the collection classes (for example, NSMutableArray,
NSMutableDictionary) are not thread-safe when mutations are concerned.
That is, if one or more threads are changing the same array, problems
can occur. You must lock around spots where reads and writes occur to
assure thread safety.
Reading this might help you out. Not totally sure if that is what is going on in your app but it looks like a good place to start.
Related
I would like to obtain the following: I have two NSOperations in a NSOperationQueue. The firs is a download from a website (gets some json data) the next is parsing that data. This are dependent operations.
I don't understand how to link them together. If they are both allocated and in the queue, how do I transfer the json string to the operation that parses it? Is it a problem if this queue is inside another NSOperationQueue that executes an NSOperation that consists of the two mentioned previously?
All I could find is transfers of data to a delegate on the main thread (performSelectorOnMainThread), but I need all this operations to execute in the background.
Thanks.
Code:
NSDownload : NSOperation
- (instancetype)initWithURLString:(NSString *)urlString andDelegate:(id<JSONDataDelegate>)delegate
{
self = [super init];
if (self) {
_urlStr = urlString;
_delegate = delegate; /// this needs to be a NSOPeration
_receivedData = [NSMutableData dataWithCapacity:256];
}
return self;
}
#pragma mark - OVERRIDE
- (void)main
{
#autoreleasepool {
if (self.isCancelled) {
return;
}
NSURL *url = [NSURL URLWithString:self.urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (self.isCancelled) {
[connection cancel];
self.receivedData = nil;
return;
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.isCancelled) {
self.receivedData = nil;
return;
}
// return data to the delegate
NSDictionary *responseDict = #{JSON_REQUESTED_URL : self.urlStr,
JSON_RECEIVED_RESPONSE : self.receivedData};
[(NSObject *)self.delegate performSelectorOnMainThread:#selector(didReceiveJSONResponse:) withObject:responseDict waitUntilDone:NO]; // ok to uses performSelector as this data is not for use on the main thread ???
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// return error to the delegate
[(NSObject *)self.delegate performSelectorOnMainThread:#selector(didFailToReceiveDataWithError:) withObject:error waitUntilDone:NO];
}
#user1028028:
Use the following approach.
1) Maintain the operation queue reference that you are using to add DownloadOperation.
2) In connectionDidFinishLoading method, create ParseOperation instance, set the json data and add it to operation queue. Maintain ParseOperation strong reference variable in DownloadOperation and handling of cancelling of parsing operation through DownloadOperation interface.
3) After completed parsing call the UI functionality in main thread.
I hope this helps.
As lucianomarisi notes, it would usually be best to just have the first operation generate the second operation. This is usually simpler to manage. Operation dependencies aren't really that common in my experience.
That said, it's of course possible to pass data between operations. For instance, you could create a datasource property on the second operation. That would be the object to ask for its data; that object would be the first operation. This approach may require locking, though.
You can also create a nextOp property on the first operation. When it completes, it would call setData: on the second operation before exiting. You probably wouldn't need locking for this, but you might. In most cases it would be better for the first operation to just schedule the nextOp at this point (which again looks like lucianomarisi's answer).
The point is that an operation is just an object. It can have any methods and properties you want on it. And you can pass one operation to another.
Keep in mind that since an operation runs in the background, there's no reason you need to use the asynchronous interface to NSURLConnection. The synchronous API (sendSynchronousRequest:returningResponse:error: is fine for this, and much simpler to code. You could even use a trivial NSBlockOperation. Alternately, you can use the asynchronous NSURLConnection interface, but then you really don't need an NSOperation.
I also notice:
_receivedData = [NSMutableData dataWithCapacity:256];
Is it really such a small piece of JSON data? It's hard to believe that this complexity is worth it to move such a small parsing operation to the background.
(As a side note, unless you know precisely the size of the memory, there's not usually much benefit to specifying a capacity manually. Even then it's not always clear that it's a benefit. I believe NSURLConnection is using dispatch data under the covers now, so you're actually requesting a memory block that will never be used. Of course Cocoa also won't allocate it because it optimizes that out... the point is that you might as well just use [NSMutableData data]. Cocoa is quite smart about these kinds of things; you generally can only get in the way of its optimizations.)
As Rob said, unless you have any particular reason to use operations use the synchronized call. Then perform the selector on MainThread or on any other thread you need. Unless you want to separate the retrieval and parsing in separate operations or thread (explicitly).
Here is the code I was using for json retrieval and parsing:
-(BOOL) loadWithURL:(NSString*) url params: (NSDictionary*) params andOutElements:(NSDictionary*) jElements
{
NSError *reqError = nil;
NSString* urlStr = #"";//#"http://";
urlStr = [urlStr stringByAppendingString:url];
NSURL* nsURL = [NSURL URLWithString:urlStr];
//Private API to bypass certificate ERROR Use only for DEBUG
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[nsURL host]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: nsURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"";
if(params!=nil) {
NSEnumerator* enumerator = params.keyEnumerator;
NSString* aKey = nil;
while ( (aKey = [enumerator nextObject]) != nil) {
NSString* value = [params objectForKey:aKey];
//Use our own encoded implementation instead of above Apple one due to failing to encode '&'
NSString* escapedUrlString =[value stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
//Required to Fix Apple bug with not encoding the '&' to %26
escapedUrlString = [escapedUrlString stringByReplacingOccurrencesOfString: #"&" withString:#"%26"];
//this is custom append method. Please implement it for you -> the result should be 'key=value' or '&keyNotFirst=value'
postString = [self appendCGIPairs:postString key:aKey value:escapedUrlString isFirst:false];
}
}
//************** Use custom enconding instead !!!! Error !!!!! **************
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&reqError];
if(reqError!=nil) {
NSLog(#"SP Error %#", reqError);
return NO;
}
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//Handles Server Errors during execution of the web service that handles the call.
if([json_string hasPrefix:#"ERROR"] == YES){
NSLog(#"SP Error %#", lastError);
return NO;
}
//Very Careful!!!!!! Will stop for any reason.!!!!!!
//Handles errors from IIS Server that serves teh request.
NSRange range = [json_string rangeOfString:#"Runtime Error"];
if(range.location != NSNotFound) {
NSLog(#"SP Error %#", lastError);
return NO;
}
//Do the parsing
jElements = [[parser objectWithString:json_string error:nil] copy];
if([parser error] == nil) {
NSLog(#"Parsing completed");
} else {
jElements = nil;
NSLog(#"Json Parser error: %#", parser.error);
NSLog(#"Json string: %#", json_string);
return NO;
}
//Parsed JSON will be on jElements
return YES;
}
i'm quite a beginner at cocoa an objective-c - so please forgive me a possibly trivial question.
I'm currently working on an XCODE-Project which is fetching some data via NSJSONSerialization and store it for further work.
At this step I'm going to encapsulate the progress of fetching the data into an class which has some setter for the needed parameters (url to fetch from and the layer which should be parsed into an array). In order to use this procedure im creating the method inside this class which creates a connection and a request and returns the array which should contain the data. After some tests I tried to create an instance of this class and called the method which starts to fetch the data.
My problem is, that after calling the method data_array from my new instance "block_stats"
and store the data in an array of the same type - the array is empty
table_data = [block_stats data_array];
The reason of this behavior is that the usage of the methods in (didReceiveResponse,didReceiveData,connectionDidFinishLoading) are working asynchron and the return of the data_array was done before the download was finished.
the method inside the class which contains the downloading part:
- (NSMutableArray *)data_array
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if(data_array)
{
[data_array removeAllObjects];
} else {
data_array = [[NSMutableArray alloc] init];
}
NSURLRequest *request = [NSURLRequest requestWithURL:data_url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webdata = [[NSMutableData alloc]init];
}
return data_array;
}
the IBAction in another view which creates the instance and calls the method to fetch the data
- (IBAction)refresh:(UIBarButtonItem *)sender {
KDJSONparser *block_stats = [[KDJSONparser alloc]init];
[block_stats setURL:[NSURL URLWithString:#"*JSONDATA_URL*"]];
[block_stats setLayer:#"blocks"];
table_data = [block_stats data_array];
}
I would be very glad if anyone could give some advice. It would be very nice if it would be as easy as possible to understand for me. Thanks in advance!
The solution to your problem lies in delegation (As the word suggests you will be appointing some one else to take action when a situation presents itself.)
You have already used this in the following piece of your code.
NSURLRequest *request = [NSURLRequest requestWithURL:data_url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
Here when you have set self as the delegate for your NSURLConnection you are telling the compiler to send you any appropriate messages related to the connection. These messages include didReceiveResponse,didReceiveData,connectionDidFinishLoading.
So let's implement these methods in your class and they will look something like this.
KDJSONParser.m
- (NSMutableArray *)fetchData
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURLRequest *request = [NSURLRequest requestWithURL:data_url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webdata = [[NSMutableData alloc]init];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[webdata setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[webdata appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
//Parse the webdata here. Your array must be filled now.
[self parseTheJSONData];
}
-(void)parseTheJSONData
{
//Do your parsing here and fill it into data_array
[self.delegate parsedArray:data_array];
}
And in your other class add this line in you refresh method
block_stats.delegate = self;
and implement
-(void)parsedArray:(NSMutableArray *)data_array;
I've read through tons of messages saying the same thing all over again : when you use a NSURLConnection, delegate methods are not called. I understand that Apple's doc are incomplete and reference deprecated methods, which is a shame, but I can't seem to find a solution.
Code for the request is there :
// Create request
NSURL *urlObj = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlObj cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
if (![NSURLConnection canHandleRequest:request]) {
NSLog(#"Can't handle request...");
return;
}
// Start connection
dispatch_async(dispatch_get_main_queue(), ^{
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; // Edited
});
...and code for the delegate methods is here :
- (void) connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Receiving response: %#, status %d", [(NSHTTPURLResponse*)response allHeaderFields], [(NSHTTPURLResponse*) response statusCode]);
self.data = [NSMutableData data];
}
- (void) connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed: %#", error);
[self _finish];
}
- (void) connection:(NSURLConnection *)_connection didReceiveData:(NSData *)_data {
[data appendData:_data];
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)_connection destinationURL:(NSURL *) destinationURL {
NSLog(#"Connection done!");
[self _finish];
}
There's not a lot of error checking here, but I've made sure of a few things :
Whatever happens, didReceiveData is never called, so I don't get any data
...but the data is transfered (I checked using tcpdump)
...and the other methods are called successfully.
If I use the NSURLConnectionDownloadDelegate instead of NSURLConnectionDataDelegate, everything works but I can't get a hold on the downloaded file (this is a known bug)
The request is not deallocated before completion by bad memory management
Nothing changes if I use a standard HTML page somewhere on the internet as my URL
The request is kicked off from the main queue
I don't want to use a third-party library, as, ultimately, these requests are to be included in a library of my own, and I'd like to minimize the dependencies. If I have to, I'll use CFNetwork directly, but it will be a huge pain in the you-know-what.
If you have any idea, it would help greatly. Thanks!
I ran into the same problem. Very annoying, but it seems that if you implement this method:
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
Then connection:didReceiveData: will never be called. You have to use connectionDidFinishLoading: instead... Yes, the docs say it is deprecated, but I think thats only because this method moved from NSURLConnectionDelegate into NSURLConnectionDataDelegate.
I like to use the sendAsynchronousRequest method.. there's less information during the connection, but the code is a lot cleaner.
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data){
//do something with data
}
else if (error)
NSLog(#"%#",error);
}];
From Apple:
By default, a connection is scheduled on the current thread in the
default mode when it is created. If you create a connection with the
initWithRequest:delegate:startImmediately: method and provide NO for
the startImmediately parameter, you can schedule the connection on a
different run loop or mode before starting it with the start method.
You can schedule a connection on multiple run loops and modes, or on
the same run loop in multiple modes.
Unless there is a reason to explicitly run it in [NSRunLoop currentRunLoop],
you can remove these two lines:
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];
or change the mode to NSDefaultRunLoopMode
NSURLConnection API says " ..delegate methods are called on the thread that started the asynchronous load operation for the associated NSURLConnection object."
Because dispatch_async will start new thread, and NSURLConnection will not pass to that other threat the call backs, so do not use dispatch_async with NSURLConnection.
You do not have to afraid about frozen user interface, NSURLConnection providing only the controls of asynchronous loads.
If you have more files to download, you can start some of connection in first turn, and later they finished, in the connectionDidFinishLoading: method you can start new connections.
int i=0;
for (RetrieveOneDocument *doc in self.documents) {
if (i<5) {
[[NSURLConnection alloc] initWithRequest:request delegate:self];
i++;
}
}
..
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
ii++;
if(ii == 5) {
[[NSURLConnection alloc] initWithRequest:request delegate:self];
ii=0;
}
}
One possible reason is that the outgoing NSURLRequest has been setup to have a -HTTPMethod of HEAD. Quite hard to do that by accident though!
I have a login method. Inside the method I use NSURLConnection to login and I would like the return the NSData response. The problem is that I return the NSData before the connection actually gets the data.
- (NSData*)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[responseData appendData:data]; //responseData is a global variable
NSLog(#"\nData is: %#", [[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding]autorelease]);//this works
isLoaded = YES; //isLoaded is a BOOL
}
- (NSData*)login:(NSString*)username withPwd:(NSString*)password{
isLoaded = NO;
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
if(connection){
NSLog(#"Connected");
}
while(isLoaded = NO){
[NSThread NSSleepForTimeInterval: 1];
}
isLoaded = NO;
return responseData;
}
The program gets stuck at the while loop, but without the while loop the program can retrieve the data from the server, it is just that the method seems to return responseData, before the delegate method changes it.
So my question is how can I make it so the method will return the responseData only after the server is done with it ?
Unless otherwise specified, NSURLConnection loads a URL asynchronously. It uses deleegate callbacks to update the delegate about the progress of the URL download.
Specifically, Utilize NSURLConnection delegate's connectionDidFinishLoading: method. Your NSURLConnection object will call this once all the data has been loaded. It is within this method that you can return your data.
You can load the data synchronously but you may end up blocking UI.
Good luck!
You should refactor your code.
You are using a asynchronous call (good), but you try to handle it synchronously (not so good — if not using a separate thread).
to use an asynchronous behavior, you need a callback, in cocoa-fashion this is usually a delegate method (or could be a block for newer code). Actually it is your connection:didReceiveData. this method will work with the returned data — not the one, where you started the request. therefor usually methods, that start a asynchronous request, do not return anything — and for sure not, what is expected to be return form the request.
- (void)login:(NSString*)username withPwd:(NSString*)password
{
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
//Note: you cannot change the delegate method signatures, as you did (your's returns an NSData object)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data]
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Now that the connection was successfully terminated, do the real work.
}
look at this apple example code.
You can use the sync request method
- (NSData*)login:(NSString*)username withPwd:(NSString*)password
{
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]
return responseDate;
}
Documentation:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/occ/clm/NSURLConnection/sendSynchronousRequest:returningResponse:error:
I am attempting to write a bit of code that checks the URL of a datasource, then populates an array with objects from that URL. It actually works well, but if there is a problem with the web connection or the address I want to populate the array with data from a bundled file. The issue I am having is that the connection didFailWithError method is never called. I tried passing a simple string but it does not call. I want the app to still function for people who are using ipod touch or are in airplane mode.
connection didReceiveResponse is working without issue.
This is what I'm working with.
- (void)loadListData{
NSLog(#"Loading data from sources");
NSURLRequest *listURLRequest = [NSURLRequest requestWithURL:integerPhoneListURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0];
[[NSURLConnection alloc] initWithRequest:listURLRequest delegate:self];
if (!listConnectFail){
phoneListJSON =[NSData dataWithContentsOfURL:integerPhoneListURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:phoneListJSON waitUntilDone:YES];
} else {
//This will tell us if there is an error loading the file
NSLog(#"File not found on web init from file");
phoneListJSON =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"contactlist" ofType:#"json"]];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:phoneListJSON waitUntilDone:YES];
}
//Initialize the filtered list with array of customer objects. Based on original data
filteredList = [[NSMutableArray alloc] init];
for (NSDictionary *dict in phoneListOriginal) {
contact *single = [[contact alloc] init];
single.fName = [dict objectForKey:#"fName"];
single.lName = [dict objectForKey:#"lName"];
single.extension = [dict objectForKey:#"extension"];
single.title = [dict objectForKey:#"title"];
single.department = [dict objectForKey:#"department"];
single.cellNumber = [dict objectForKey:#"cellNumber"];
//NSLog(#"%#", single.lName);
[filteredList addObject:single];
}
NSLog(#"Array filteredLIst contains %d records",[filteredList count]); }
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
listConnectFail = YES;
NSLog(#"Connection Failed, pulling from file"); }
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
listConnectFail = NO;
NSLog(#"Connection Succeeded, populating from API");
}
I know it is probably something stupid that I am not seeing, but I could use the help to see what I don't
Thanks in advance!
How did you confirm that your delegate did not receive the message? Did you check the log?
Your code seems to assume that 'listConnectFail' will be set immediately after the NSURLConnection's init is done, which is not necessarily the case.
[[NSURLConnection alloc] initWithRequest:listURLRequest delegate:self];
if (!listConnectFail){...}
The NSURLConnection documentation states that 'The delegate will receive delegate messages as the load progresses.'
However, I am not sure about the airplane mode, maybe this particular error can be detected synchronously.