On 8 Apr 2011, at 7:51 PM, Kyle Sluder wrote:

> As explained in the Blocks Programming Guide, you should not allow
> blocks that reference stack storage to escape that scope. See
> "Patterns to Avoid":
> http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html

I am grateful you called this to my attention, as I had been thinking that 
blocks were closures, in which referencing (but not, usefully, changing) 
stack-local variables would work. I'd been thrown by the existence of the 
__block attribute, which permits referencing a stack-local variable as an 
lvalue. I had reasoned that if a __block variable _is_ obviously a reference to 
that memory, a non-__block variable (whose value does _not_ propagate to the 
stack variable when a block changes it) obviously _couldn't_ be a reference.

One of the examples is:

void dontDoThis() {
    void (^blockArray[3])(void);  // an array of 3 block references
 
    for (int i = 0; i < 3; ++i) {
        blockArray[i] = ^{ printf("hello, %d\n", i); };
        // WRONG: The block literal scope is the "for" loop
    }
}

... which would be useful, and a perfectly sensible thing to want to do. I'd 
hope the block literal would copy the stack context to the block structure, 
cutting the block free of its initialization context. As in fact it does for 
NSObjects.

So my question is: Can a block be made to do that useful and perfectly sensible 
thing I'd thought it did? Is the only solution wrapping the value in an NSValue?

        — F

_______________________________________________

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to