Looks like I haven't figured out the concept of blocks ...
In my code, I have to get JSON data from asychronous block , which will be returned using the outer method. I googled and found that if the definition of a variable with __block , v̶i̶s̶i̶b̶i̶l̶i̶t̶y̶ _mutability_ of , this variable extends to block .
But for some reason, the returned json object is nil.I wonder why?
- (NSMutableDictionary *)executeRequestUrlString:(NSString *)urlString { __block NSMutableDictionary *json = nil; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPShouldHandleCookies:YES]; [request setHTTPMethod:@"GET"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"]; NSString *cookieString = [self.userDefaults objectForKey:SAVED_COOKIE]; [request addValue:cookieString forHTTPHeaderField:@"Cookie"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); NSError *error1; NSMutableDictionary * innerJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error1]; json = innerJson; }]; return json; }
source share