4

I'm trying to instantiate new windows programmactially, then configure their delegate object.

Unfortunatelly, the delegate object does not seems to receive any event once set.

I've tried to reduce my code to a short example:

AppDelegate.h

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate>
- (IBAction) clicked:(id)sender;
@end

AppDelegate.m

@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end

@implementation AppDelegate {
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Main app window delegate works properly
    [[self window] setDelegate:self];
}

// Button clicked: instantiate a new window from a specific nib (default)
- (IBAction) clicked:(id)sender {
    static NSWindowController* foo;

    foo = [[NSWindowController alloc] initWithWindowNibName: @"ExampleWindow"];
    [[foo window] setDelegate:self];
    [foo showWindow:self];
}


// Will correctly trigger for main window, but not for newly created windows
- (void) windowWillMove:(NSNotification *)notification {
    NSWindow* moved = (NSWindow*)[notification object];
    NSLog(@"Window %p (%@) will move", moved, [moved title]);
}

@end

I'm probably missing something obvious, but I'm unable to determine what

Romuald Brunet
  • 5,595
  • 4
  • 38
  • 34
  • Don't you set it in Interface Builder? – trojanfoe Jan 01 '16 at 11:23
  • @trojanfoe correct, it seems that using *setDelegate* will not register the notifications, but setting it in IB will work. I've tried that in my original code, but the *NSWindowController* was not referenced correctly (instead I only referenced it's *NSWindow*. Thank you! – Romuald Brunet Jan 01 '16 at 12:33

1 Answers1

0

Here's the only reliable solution for assigning the window delegate programmatically: after calling show() on the window, create a timer that will fire after one second, and in that timer's method, assign the delegate. You may need to adjust the timer interval, depending on how long it takes to construct that particular window.

See How do I use NSTimer? for an example of using timers in Objective-C.

Jason McClinsey
  • 426
  • 5
  • 12