why does __block not adding values to array

58 Views Asked by At

I am enumerating ranges inside a block and storing the values inside an array. I expected using __block should store the values inside block into array?

 __block  NSMutableArray *array;
  [indexSet enumerateRangesUsingBlock:^(NSRange range,BOOL * stop ) {

    [array addObject:@(range.location)];
    [array addObject:@(range.length)];

     NSLog(@"location is %d, %ld", range.location, range.length);


}];


NSLog(@"%@",array );

But this result in

location is 4, 2 location is 8, 2 location is 14, 2

and for array

(null)

I expected array to be filled with values.

2

There are 2 best solutions below

1
On BEST ANSWER

You have to initialize it, a just declared array is nil:

__block  NSMutableArray *array = [NSMutableArray array];

(The Swift compiler would throw an error ... )

1
On

__block NSMutableArray *array = [NSMutableArray array];

It does work fine.

However when I declared array as property then block became redundant.