Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use pointers to change values in blocks?

I've started using blocks, and one of the first things I encountered is an inability to set values which are captured by the closure. This is fine, I've been using C/C++ a long time. I'll just use pointers!

MyObject* bestObj = nil;
float bestDist= 10000.f;

MyObject **pBestObj = &bestObj;
float* pBestDist = &bestDist;

[self testObjects:class block:^(MyObject* obj){

        CGRect r = [obj boundingBox];
        // position is captured from outside this code sample
        if( CGRectContainsPoint( r, position ) )
        {
            float dist = GetDistance( obj, position );

            if(dist < bestDist)
            {
                *pBestDist = dist;
                *pBestObj = obj;
            }
        }
}];

return bestObj;

My question is, is this safe? I assume that as long as my pointer points to something that hasn't gone out of scope and that still exists, that it should work. But I'm also assuming that things that take blocks don't ever, say, run them in parallel. I know my code doesn't, but I don't know about, say, using a block with an NSArray enumerateObjectsUsingBlock call.

like image 538
Charles Randall Avatar asked Jul 16 '11 22:07

Charles Randall


1 Answers

The 'right' way to do this would be to mark those original variables as block mutable, __block

like image 142
Joshua Weinberg Avatar answered Oct 18 '22 02:10

Joshua Weinberg