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.

2
  • You might want to alloc/init the array first. Commented Apr 26, 2018 at 8:17
  • 1
    The __block is not needed, even once you do allocate the array. Commented Apr 26, 2018 at 18:01

2 Answers 2

1

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

__block  NSMutableArray *array = [NSMutableArray array];

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

Sign up to request clarification or add additional context in comments.

1 Comment

Vadian, you forgot to explain that the __block is redundant
0

__block NSMutableArray *array = [NSMutableArray array];

It does work fine.

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

1 Comment

__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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.