Note that there are some explanatory texts on larger screens.

plurals
  1. POaddObserverForName and removing observer
    text
    copied!<p>On Cocoa code with ARC enabled, I tried to observe Window closing events like below.</p> <pre><code>ScanWindowController * c = [[ScanWindowController alloc] initWithWindowNibName:@"ScanWindowController"]; [scanWindowControllers addObject:c]; [c showWindow:nil]; NSMutableArray *observer = [[NSMutableArray alloc] init]; observer[0] = [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification object:nil queue:nil usingBlock:^(NSNotification *note) { [scanWindowControllers removeObject:c]; [[NSNotificationCenter defaultCenter] removeObserver:observer[0]]; }]; </code></pre> <p>I thought this will remove all the references to the controller (c) after closing Window. But actually, this code does not dealloc ScanWindowController after closing Window. If I wrote like below using weak reference to the controller, dealloc of ScanWindowController is called.</p> <pre><code>ScanWindowController * c = [[ScanWindowController alloc] initWithWindowNibName:@"ScanWindowController"]; [scanWindowControllers addObject:c]; [c showWindow:nil]; __weak ScanWindowController * weak_c = c; NSMutableArray *observer = [[NSMutableArray alloc] init]; observer[0] = [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification object:nil queue:nil usingBlock:^(NSNotification *note) { [scanWindowControllers removeObject:weak_c]; [[NSNotificationCenter defaultCenter] removeObserver:observer[0]]; }]; </code></pre> <p>Why does the first code not work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload