John Bale
John Bale

Reputation: 443

Return a variable from inside a block

Below I have some code which should return an array, the response from the server happens in a block:

- (NSMutableArray *)getArray
{
    NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                  @"pending", @"command",
                                  @"2" , @"userID",
                                  nil];

    [[API sharedInstance] commandWithParams:params
                               onCompletion:^(NSDictionary *json) {
                                   //result returned


                                   if ([json objectForKey:@"error"]==nil) {
                                       NSMutableArray *res = [[NSMutableArray alloc] init];
                                       [res addObject:@"1234"];

                                       RETURN HERE

                                   } else {
                                       //error
                                       [UIAlertView title:@"Error" withMessage:[json objectForKey:@"error"]];
                                   }

                               }];
}

After parsing the data and creating an array I want to return the array I have created for the getArray method call. So far, after hours of trying I have not had any luck, even with trying some suggestions from previous questions on stackoverflow. Any help would be appreciated.

Upvotes: 1

Views: 114

Answers (2)

Tobi
Tobi

Reputation: 5519

I'd create a method in somewhere in the class let's say - (void)arrayFetched:(NSArray *)fetchedArray.

Then you modify your code like this:

//...
if ([json objectForKey:@"error"]==nil) {
    __weak NSMutableArray *res = [[NSMutableArray alloc] init];
    [res addObject:@"1234"];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self arrayFetched:[res copy]];
    });
    //...

and then do want you want with the array in the arrayFetched: method.

Upvotes: 1

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

pass the block as a param to the function

- (NSMutableArray *)getArray:(void (^)(NSArray *))block {}

And then replace the RETURN HERE with block(res);

Upvotes: 3

Related Questions