Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an object from a class that uses NSURLConnection and it's delegate classes?

I'm in the process of trying to move code from a UITableViewController class to a "helper" class.

The code utilizes NSURLConnection to grab and parse JSON and then populate an NSMutableArray.

What I'd like to do is call a method in my helper class that returns a NSMutableArray. What I don't understand is how to return the array from the connectionDidFinishLoading delegate class of NSURLConnection (where the array is actually built) as though it was from the originally called method that started the connection. In other words, how does the method that calls NSURLConnection get control back so it can return a value from the whole operation?

Here are the relevant methods from the helper class. How do I get the getMovies method to return the listOfMovies that is built in the connectionDidFinishLoading delegate class?

-(NSMutableArray)getMovies:(NSURL*)url {

responseData = [[NSMutableData data] retain];       

NSURLRequest *request = [NSURLRequest requestWithURL:url];
//NSURLRequest* request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 30.0];

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//TODO error handling for connection
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {      

//---initialize the array--- 

listOfMovies = [[NSMutableArray alloc] init];

tmdbMovies = [[NSArray alloc] init];
posters = [[NSArray alloc] init];
thumbs = [[NSDictionary alloc] init];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

SBJsonParser *json = [[SBJsonParser new] autorelease];

tmdbMovies = [json objectWithString:responseString];

// loop through all the top level elements in JSON
for (id movie in tmdbMovies) {

    // 0 - Name
    // 1 - Meta
    // 2 - Url


    if ((NSNull *)[movie objectForKey:@"name"] != [NSNull null]) {

        if (![[movie objectForKey:@"name"] isEqualToString:@""]) {
            name = [movie objectForKey:@"name"];
        }

    } 

    if ((NSNull *)[movie objectForKey:@"info"] != [NSNull null]) {

        if (![[movie objectForKey:@"info"] isEqualToString:@""]) {
            meta = [movie objectForKey:@"info"];
        }

    } 

    if ((NSNull *)[movie objectForKey:@"thumb"] != [NSNull null]) {

        if (![[movie objectForKey:@"thumb"] isEqualToString:@""]) {
            thumbUrl = [movie objectForKey:@"thumb"];
        }

    } 

    NSLog(@"Name: %@", name);
    NSLog(@"Info: %@", meta);
    NSLog(@"Thumb: %@", thumbUrl);

    NSMutableArray *movieData = [[NSMutableArray alloc] initWithObjects:name,meta,thumbUrl,nil];

    // add movieData array to listOfJMovies array
    [listOfMovies addObject:movieData];


    [movieData release];
}


//FIXME: Connection warning
if (connection!=nil) { 
    [connection release]; 
}

[responseData release]; 
[responseString release];



}
like image 480
user558096 Avatar asked Jan 05 '11 19:01

user558096


2 Answers

What you really need to do here is create a @protocol that creates a delegate for your helper class. Then change -(NSMutableArray)getMovies:(NSURL*)url to -(void)getMovies:(NSURL*)url

The class that is calling your helper method needs to implement your helper method's delegate.

Then - (void)connectionDidFinishLoading:(NSURLConnection *)connection calls the delegate method(s). It's best to have a one for success and one for failure.

=Update Begin=

You will need to also define an id delegate in your helper file which the calling class sets to self after init but before calling -(void)getMovies:(NSURL*)url. That way the helper file knows where to call back to.

getMovies *movieListCall = [[getMovies alloc] init];
movieListCall.delegate = self;
[movieListCall getMovies:<your NSURL goes here>];

You will see some additional lines for the inclusion of a delegate in both the getMovies.h and getMovies.m files.

=Update End=

in your getMovies.h file add:

@protocol getMoviesDelegate

@required
- (void)getMoviesSucceeded:(NSMutableArray *)movieArray;
- (void)getMoviesFailed:(NSString *)failedMessage;

@end

@interface getMovies : NSOBject {
id delegate;
}

@property (nonatomic, assign) id delegate;

in your getMovies.m file add:

@synthesize delegate;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //TODO error handling for connection
    if ([delegate respondsToSelector:@selector(getMoviesFailed:)]) {
        [delegate getMoviesFailed:[error localizedDescription]];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {      

//finishes with
    if ([delegate respondsToSelector:@selector(getMoviesSucceeded:)]) {
        [delegate getMoviesSucceeded:listOfMovies];
    }
}

update your calling class .h file to use getMoviesDelegate:

@interface MoviesView : UIViewController <getMoviesDelegate>{
.
.
.
}

add the getMoviesDelegate methods to your calling class .m file

- (void)getMoviesSucceeded:(NSMutableArray *)movieArray {
//deal with movieArray here
}

- (void)getMoviesFailed:(NSString *)failedMessage {
//deal with failure here
}

This is not tested but hopefully gives you a road map to work with.

Protocols are nice because you can make both required and optional delegate methods and it helps in refining your helper methods to become very reusable across projects. The compiler will also warn you if you have implemented a protocol but not implemented the protocol's required delegate methods. If you follow this path be sure to use conformsToProtocol: and respondsToSelector:

like image 155
dredful Avatar answered Oct 13 '22 01:10

dredful


Fundamentally, what's happening is that you're starting an asynchronous network load (asynchronous is the right way to do this, almost assuredly), and then you need some way to resume whatever operation you were doing before the load began. You have a few options:

  • Create your own delegate protocol. Your UITableViewController would then set itself as the helper's delegate, and the helper would call helperDidLoad or whatever you named that method. There's more information on writing delegates in the Cocoa Programming Guide.

  • Use blocks and continuation passing style. This is a bit more advanced but I like it. In your UITableViewController you'd write something like this:

     [helper doSomething:^ (id loaded) { 
         [modelObject refresh:loaded]; // or whatever you need to do
     }];
    

    And then in your helper you'd write:

     - (void)doSomething:(void ^ (id))continuation {
         _continuation = continuation;
         //kick off network load
     }
    
    
     - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
         _continuation(_data);
     }
    
  • Use notifications. Read the NSNotificationCenter docs.
  • Use KVO. The KVO programming guide has a lot of good info on Key-Value Observing.
like image 29
Colin Barrett Avatar answered Oct 12 '22 23:10

Colin Barrett