Q:

Write to variable outside of block in objective c

I'm using NSRegularExpression enumerateMatchesInString]. 
I'm passing it an inline block. 
The block is called each time a result is found. I'd like to create a new string by appending the results one after the other to the new string. 
I can't access variables outside the block (apparently). I can't return a value from the block since enumerateMatchesInString expects the block to have return type void.
I can't believe using properties of the class is the best practice here...
How do I do this? 

A:

There is nothing wrong in accessing properties in a block, but you have to be careful.
by default blocks capture variables strongly. if the class now holds the block, you get an retain cycle. 
To avoid this, you can create a weak variable of self. in the block you than create a (default) strong variable to avoid, that the object self will be released while processing the block
__weak typeof(self) weakSelf = self;
self.testBlock = ^(NSInteger itemIndex) {
    typeof(self) strongSelf = weakSelf;
    if(strongSelf){
         strongSelf.foo = ....;
    }
};

if you want to write to a variable from the surrounding scope, you use __block.
__block NSUInteger foundIndex = NSNotFound;

[array enumerateObjectsUsingComparator:^(id obj, NSUInteger idx, *BOOL stop){
    if([obj ....]){
        foundIndex = idx;
        *stop = YES;
    }
}];

