Nicolò Ciraci
Nicolò Ciraci

Reputation: 678

__block ivar is always (null)

I've writen a class to parse XML on block. The completionHandler return an mutableArray and an error (if it happens), the problem is that I can NSLog the element of the array but if I init a __block NMutableArray with the array it return null:

__block NSMutableArray *imagesURLs;
   NCBlockParser *parser = [[NCBlockParser alloc] init];
   [parser parseXMLFromURL:url withElementsName:[NSArray arrayWithObject:@"element"] completionHandler:^(NSMutableArray *item, NSError *err) 
    {
    if (err) {
        NSLog(@"%@",[err localizedDescription]);
    }
    else {
        imagesURLs = [[NSMutableArray alloc] initWithArray:item];
    }
    }];

   NSLog(@"%@",imagesURLs); // (null) here :(

Ideas?

Upvotes: 1

Views: 166

Answers (1)

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

So, you have some confusion about how blocks work.

The NSLog line is run long before the block is ever executed. Your imagesURL variable is only filled out after your parse returns, which is being done asynchronously. Move that NSLog inside the block and you should see what you're expecting.

Upvotes: 2

Related Questions