user1205315
user1205315

Reputation: 47

IOS 5.0 - NSURLConnection works but returns Null before completing

I have a class file called functions where I keep repetitive tasks. One of the functions in there is called GetPrice which connects to an XML web service, parses the XML and returns a CarPrice object. Everything works great until it's time to return the CarPrice object. It is NULL even though in my connectionDidFinishLoading, the object is not null.

Here is my GetPrice function:

-(CarPrice*)GetPrice:(NSString *)m
{
    NSString *url =[@"http://myUrl.com"];

    dataWebService = [NSMutableData data];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
    return mp;  //mp is declared as a CarPrice in the @interface section of my funcs class

    //when it gets returned here it is NULL even though....(see below)
}


//Connection Functions=======================


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

    [dataWebService setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [dataWebService appendData:data];
}

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

    NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
    ParserMetal *pmr = [ParserMetal alloc];
    mp = [pmr parseMetal:responseString];
    //at this point, the mp is fully populated
    //an NSLOG(@"%@", mp.displayPrice); here will show that the mp object is populated
    //however as stated above, when it returns, it is null.
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Error during Connection: %@", [error description]);
}

//End Connection Functions ==================

Is the return mp; happening before the mp gets populated? Do I need to use a Synchronous connection here to make sure the data is populated before the return?

Upvotes: 3

Views: 832

Answers (1)

Robbietjuh
Robbietjuh

Reputation: 868

If I understand your code correctly, you are going to call GetPrice:m: and then start the connection from there. After you start the connection by using [connection start], you immediately return mp.

This means that the connection is started, but before it has received all its data, you already return mp. You should wait for the data to be received, and then return mp.

You could use a Synchronous method for this, or you could implement a method in your main class, which is going to be called from within the connectionDidFinishLoading:connection: method, defined in your 'other class file'. Like this:

  • Start connection
  • Receive data...
  • Call [mainClass didReceiveAllData:mp]

Hope this helps.

Upvotes: 2

Related Questions