> On 12 Jul 2017, at 17:41, Jens Alfke <j...@mooseyard.com> wrote:
> 
>> On Jul 12, 2017, at 9:34 AM, Jeremy Hughes <moon.rab...@virginmedia.com> 
>> wrote:
>> 
>> // Prints "Why is childReference not nil?”
> 
> There may still be a reference in the autorelease pool. Check childReference 
> again ‘later’, i.e. on the next user event or after a timer/delayed-perform.

Jens is correct. Here’s a modified version of the playground code that adds an 
autorelease pool:

import Cocoa

let parent = NSViewController()
var child: NSViewController? = NSViewController()
weak var childReference: NSViewController? = child

autoreleasepool
{
        parent.addChildViewController(child!)
        
        child = nil
        
        parent.childViewControllers = []
}

if childReference == nil
{
        print("childReference is nil")
}
else
{
        print("Why is childReference not nil?")
}

// Prints "childReference is nil"

I’m still not entirely clear on when autorelease pools are used in Swift. There 
is a WWDC video which says that they’re used in code that interfaces with 
Objective-C, but Greg Parker’s comments in this thread indicate that 
autorelease is also used behind the scenes in native Swift code - except that 
in many cases the compiler is able to optimise it out of existence. Apple’s 
Swift book doesn’t mention autorelease.

For practical purposes, it seems that you need to be aware of autorelease pools 
when using Cocoa (or Objective-C) objects, but you don’t normally need to be 
aware of them when using native Swift objects.

Jeremy

_______________________________________________

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

Reply via email to