-1

The line of code inside blocks in objective c is executed later after executing other lines of code in the same method. My query is:

There is a method named :

-(NSDictionary*)callingWeatherService{
        NSString *urlString =  @"http://api.openweathermap.org/data/2.5/weather?q=London,uk";
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.responseSerializer = [AFJSONResponseSerializer serializer];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            // 3
            self.dictionary = (NSDictionary *)responseObject;


        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            // 4
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                message:[error localizedDescription]
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
            [alertView show];
        }];


        // 5
        [operation start];
        return self.dictionary;
}

But the statement return self.dictionary; gets executed first before block execution so dictionary is returned as nil; Is there any solution that statement return self.dictionary; is executed only after block execution. I need this approach for a specific purpose. Don't want to use delegates, I had already used delegates inside afnetworking blocks for getting dictionary data.

Larme
  • 24,190
  • 6
  • 51
  • 81
vivek_ios
  • 173
  • 3
  • 13
  • possible duplicate of [NSURLSession with NSBlockOperation and queues](http://stackoverflow.com/questions/21198404/nsurlsession-with-nsblockoperation-and-queues) – Avt May 12 '14 at 09:47
  • possible duplicate of [how to make function to return after the AFHTTPRequestOperation has done](http://stackoverflow.com/questions/14545164/how-to-make-function-to-return-after-the-afhttprequestoperation-has-done) – Martin R May 12 '14 at 09:48

1 Answers1

0

The short answer is no - blocks are designed to be performed asynchronously, meaning that you never know when they complete. It would be really dumb to change this behavior.

Either use delegates, or use KVO assigned to the dictionary variable or NSNotifications. If I were you I would definitely use delegates.

Sergey Grischyov
  • 11,995
  • 20
  • 81
  • 120
  • "blocks are designed to be performed asynchronously" Not necessarily. Blocks are just runnable things, like functions. They can be run synchronously or asynchronously or whatever. – newacct May 12 '14 at 20:00