Re: ARC, blocks, capture variables
Re: ARC, blocks, capture variables
- Subject: Re: ARC, blocks, capture variables
- From: Scott Ribe <email@hidden>
- Date: Mon, 28 Sep 2015 16:20:46 -0600
On Sep 27, 2015, at 7:51 PM, Scott Ribe <email@hidden> wrote:
>
> On Sep 27, 2015, at 7:03 PM, Quincey Morris <email@hidden> wrote:
>>
>> IIRC you can simply assign ‘self’ to a local variable just before assigning to ‘fun', and use the local variable name instead of ‘self’ inside the block.
>
> Well, that does work. Thanks!
So, a follow-up. Indeed assigning to a local var & then using it does work. Because although it creates the same retain cycle which must be broken the same way, the compiler does not catch it, and I'd be right back where I was before ARC--everything working OK.
And you can also assign to a weak local var & then use that, not create a retain cycle, and not have to break it anymore. And you can wrap that in a macro something like:
#define WeakRef(s) __weak __typeof__(s) s##_weak = s
But ultimately, I didn't really like doing things this way, nor with any type of dummy local var to fool the compiler:
WeakRef(self);
self.authfun = ^void () {[self_weak ...];};
The essential problem was in the library design, not the calls. I was keeping self.authfun as an instance var for the sole purpose of unregistering the callback when the owner (a window controller) was being torn down. The better way (IMO) was to change the basic call from:
void RegisterAuthenticationCallback(void (^)())
void UnregisterAuthenticationCallback(void (^)())
to:
void RegisterAuthenticationCallback(id, void (^)())
void UnregisterAuthenticationCallbacks(id) // note slight change in semantics, cannot unregister a single cbk
So now the callback is keyed on the owner, a simple change in the underlying class, but we're back to clients just have to register & unregister without any temp vars nor cycle-breaking.
--
Scott Ribe
email@hidden
http://www.elevated-dev.com/
https://www.linkedin.com/in/scottribe/
(303) 722-0567 voice
_______________________________________________
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