0

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.

humble_pie
  • 119
  • 10

2 Answers2

1

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

__block  NSMutableArray *array = [NSMutableArray array];

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

vadian
  • 274,689
  • 30
  • 353
  • 361
0

__block NSMutableArray *array = [NSMutableArray array];

It does work fine.

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

humble_pie
  • 119
  • 10
  • 1
    `__block` was *always* redundant. The attribute allows you to change the value of the variable `array` within your block, you are not doing that, it's value remains the same - it always references the *same* array. It is the mutable array whose content changes. – CRD Apr 28 '18 at 10:04