On Dec 6, 2013, at 9:24 AM, Seth Willits <sli...@araelium.com> wrote: > On Dec 6, 2013, at 8:05 AM, dangerwillrobinsondan...@gmail.com wrote: >>>> On 6 Dec 2013, at 11:26 am, Graham Cox <graham....@bigpond.com> wrote: >>>> >>>> NSBlockOperation* op = [NSBlockOperation >>>> blockOperationWithBlock:^ >>>> { >>>> CGContextClipToRect( ncx, tileRect ); >>>> >>>> [self drawTile:tileRect inContext:ncx]; >>>> }]; >>> >>> >>> A question for blocks experts: >>> >>> Is the value of <tileRect> here captured when the block is created,or when >>> it is run? >>> >>> If the latter, it’s going to be probably wrong most of the time, so how can >>> I make sure it is captured when the block is created? >>> >> >> >> It's the latter IIRC >> You'll want to capture it outside and prefix it to be block scoped. > > No it’s not and no you don’t.
To expand on this, whenever you evaluate a block literal expression that uses one or more normal local variables, those variables are immediately copied into the block, essentially as if the block literal were a struct with a field that looks exactly like the local variable. When you copy the block and it has to “move" to the heap, the exact same structure gets allocated there and member-by-member copied from the stack version. Any subsequent changes to the variable aren’t tracked, because how could they be? A __block variable is special; when you capture a __block variable, what’s actually captured is a pointer to the __block variable’s byref struct. I’ve seen a lot of confusion and over-use of __block variables, which can probably be traced back to the name being somewhat misleading. You don’t need to make a __block variable just to capture something in a block. You need to make a __block variable only if it’s important to you that the block and the enclosing function are working on the same variable, not just the same value; that is, if you’re going to modify the variable in one place and need those modifications to be seen by the other. The usual use case is a block that’s supposed to set some variable in the enclosing scope, but you could also imagine a function running a state machine and a long-lived block that’s supposed to react to state changes. John. _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com