Question

I have a strange problem with the NSURLConnectionDataDelegate. I have created a class for parsing of json. Here the code:

- (void)createJSONDictionaryFromURL:(NSURL *)url
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    (void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    jsonData = [[NSMutableData alloc] init];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Fail with error");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    NSLog(@"%@", self.jsonDictionary);
}   

In the Method connectionDidFinishLoading, is everything correct, the console shows the correct data. But I want to use this in the viewDidLoad Method from my ViewController.

JSONParser *parser = [[JSONParser alloc] init];
NSDictionary *dict = [[NSDictionary alloc] init];
[parser createJSONDictionaryFromURL:url];
dict = parser.jsonDictionary;

NSLog(@"%@", dict);

The console shows (null), can anybody help me?

Sorry for my bad english

Était-ce utile?

La solution

Your JSONParser is asynchronous because of the network connection (it is asynchronous). So, when you currently call parser.jsonDictionary you see that the data isn't ready yet.

You don't want to try blocking until the data is available, rather you should setup a callback to get the data to your view controller when it's ready (so you can save it and update the UI).

That could be done by adding a delegate property to your JSONParser and having the view controller assign itself and implement some callback method. Or, using less code, the JSONParser can offer a block property that the view controller sets and which is called in connectionDidFinishLoading: (make sure the @property uses (copy, nonatomic)`).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top