Re: ARC query
Re: ARC query
- Subject: Re: ARC query
- From: "Glenn L. Austin" <email@hidden>
- Date: Fri, 09 Jan 2015 07:57:25 -0800
> On Jan 7, 2015, at 1:11 PM, Mike Abdullah <email@hidden> wrote:
>
>
>> On 7 Jan 2015, at 20:55, Sean McBride <email@hidden> wrote:
>>
>> On Wed, 7 Jan 2015 12:02:16 -0600, Ken Thomases said:
>>
>>> Short answer: yes, the alert is retained.
>>
>> Meaning that one must use the weak/strong dance pattern like this?
>>
>> NSAlert *alert = [NSAlert new];
>> alert.alertStyle = NSWarningAlertStyle;
>> alert.messageText = @“Do not touch!";
>> __weak NSAlert* weakAlert = alert;
>> [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) {
>> NSAlert *strongAlert = weakAlert;
>> [strongAlert orderOut:self];
>> }];
>>
>> I miss garbage collection. None of that was necessary. I still haven't got my head around dealing with this under ARC…
>
> No, no dancing necessary. The completion block is only fired the once. After that it’s discarded, breaking the retain cycle.
I think that the key here that may have been missed is that the completion block is *explicitly* released by the dismissal of the alert, which cascades the release to all associated objects.
alert retains block which retains alert. Code exits with releases alert, but the pending block still has a retain on alert. When the block is called, alert is (likely) retained during its execution in order to call the block. Once the block is called alert releases block, which releases *its* retain on alert. The alert finishes its execution and releases itself.
The only need for the strong/weak dance is to implicitly break the object ownership cycle (strong implies ownership of the object, weak explicitly denies ownership of the object). Remember that, and strong/weak become far easier to understand. Of course, all of that assumes that the necessary data for the can be easily re-constructed on demand. And like all generalizations, this doesn't cover all of the use cases, but it may help address some of the confusion about strong/weak and retain cycles.
--
Glenn L. Austin, Computer Wizard and Race Car Driver <><
<http://www.austinsoft.com>
_______________________________________________
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