Muhammad Umar
Muhammad Umar

Reputation: 11782

Calling a block function in iPhone

I am trying to run a following Function

+(NSString *)responseFromQuery:(NSString *) queryString
{
    __block NSString *response;
    __block NSError *err = nil;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{
        response = [NSString stringWithContentsOfURL:[NSURL URLWithString:queryString] encoding:NSUTF8StringEncoding error:&err];

        dispatch_async(dispatch_get_main_queue(), ^{

            NSLog(@"%@",response);
             if (err != nil)
             {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert!"
                                                                    message:@"An Error has occurred" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

                [alertView show];
                 return response;// = @"Error";
              }

            });
        });
   // return response;
}

I want to pass the value of response after executing the block, however instead it runs the last return first , how can i make the return expression within block to run. I am using this function in an NSObject Class According to the debugging it never runs the dispatch_async queue.

Right now if i return it gives me error "Control may reach at the end of non void block"

Upvotes: 0

Views: 313

Answers (3)

Javier C
Javier C

Reputation: 725

You can't use dispatch_async and return the value inside the executed block at the same time. The async part of *dispatch_async* means the function will return immediately and will not wait for the block to finish executing. For this you would need *dispatch_sync* without the 'a'.

The problem you would have with that is that you are making a network request in your block and that could block your UI thread. I'm assuming this function is being called in the main thread.

If you want to make an asynchronous request and send the return value to the caller you can add a block parameter to your function where the sender of the message will be notified. The method would go from being:

+(NSString *)responseFromQuery:(NSString *) queryString;

To:

+ (void)responseFromQuery:(NSString *)queryString withBlock:(void (^)(NSString *result))block;

and when you have your response string you call:

block(response);

Upvotes: 0

Ravindra Bagale
Ravindra Bagale

Reputation: 17655

because you are returning return response;. because of you are returning response it is saying that "Control may reach at the end of non void block". you returning something means it is non void block. directly return on last statement of method.

Upvotes: 0

IronManGill
IronManGill

Reputation: 7226

To fully understand the implementation and working of blocks in objective c i think you should look into the following link, it explains quite a lot and it is put really simply.

Objective C Blocks - Simple Understanding

Upvotes: 1

Related Questions