iosobjective-cobjective-c-blocks

Modify global variable in Block iOS


I have blocks that loads data from a server, the problem is that I can not affect my result in a global variable in the block

[URLImages asyncRequest:RequestForPopular
                    success:^(NSData *data, NSURLResponse *response) {
                        NSLog(@"Success!");
                        NSError* error;
                        NSDictionary* json = [NSJSONSerialization
                                              JSONObjectWithData:data
                                              
                                              options:kNilOptions
                                              error:&error];
                       
                       NSArray *arrayimages;
                        arrayimages = [[[json objectForKey:@"result"] objectForKey:@"images"] objectForKey:@"_content"];
                        
                        NSMutableArray *mutArrURLss = [[NSMutableArray alloc]init];
                        for (int i=0; i<[arrayimages count];i++)
                        {
                            NSDictionary *arrayContent = [arrayimages objectAtIndex:i];
                            [mutArrURLss addObject:[arrayContent objectForKey:@"element_url"]];
                        }

                     mutArrURLs = mutArrURLss //mutArrURLs is Global
                    }
                    failure:^(NSD`enter code here`ata *data, NSError *error) {
                        NSLog(@"Error! %@",[error localizedDescription]);
                    }];

Solution

  • Create your global mutable array first:

    NSMutableArray *mutArrURLs
    

    then in viewDidLoad or even in "+(void)initialize":

    mutArrURLs = [[NSMutableArray alloc]init];
    

    Now you have an object that can be manipulated in the block. Don't create the temporary, just add the objects to this global array.

    EDIT: cannot understand why making it a static helps, but glad that worked for you.