Re: Storing a block in a CF/NSMutableDictionary?
Re: Storing a block in a CF/NSMutableDictionary?
- Subject: Re: Storing a block in a CF/NSMutableDictionary?
- From: Fritz Anderson <email@hidden>
- Date: Sun, 10 Apr 2011 09:49:37 -0500
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 (email@hidden)
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:
This email sent to email@hidden