objective-cblocknsindexsetnsblockoperation

why does __block not adding values to array


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.


Solution

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

    __block  NSMutableArray *array = [NSMutableArray array];
    

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