1

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]);
                    }];
General Grievance
  • 4,555
  • 31
  • 31
  • 45

2 Answers2

0

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.

David H
  • 40,852
  • 12
  • 92
  • 138
  • this is what I do, but it does not work, but by declaring a static variable it works – Mohamed Yahya Mzoughi Apr 24 '13 at 16:27
  • I also cannot understand why making it `static` helps. `static` on a global variable simply makes it not available to other files. Unless the OP is lying and the variable is not actually global... – newacct Apr 24 '13 at 23:16
  • @newacct it's possible there is another global variable declared in another file of the same name, and that one is nil'd after he initialized it. That's the only explanation that makes sense. – David H Apr 25 '13 at 14:14
-2

If you want to change/assign a global variable inside a block you should use __block directive when you declare the global variable. It should be like this: __block NSMutableArray *mutArrURLs;.

danypata
  • 9,895
  • 1
  • 31
  • 44