1
votes

So I'm trying to do this exercise where I need to set a delegate for the main window. The purpose is to make sure that when the user resizes the window, it's always twice as wide as it is high.

This is my AppController.h file:

#import <Cocoa/Cocoa.h>

@interface AppController : NSObject
{
    NSWindow *windowWillResize;
}

@end

and this is my AppController.m file:

#import "AppController.h"

@implementation AppController

- (id) init
{
    [super init];
    windowWillResize = [[NSWindow alloc] init];
    [windowWillResize setDelegate:self];

    return self;
}

- (NSSize) windowWillResize:(NSWindow *)sender
                 toSize:(NSSize)frameSize;
{
    NSLog(@"size is changing");
    return frameSize;
}

@end

However, I can remove the line [windowWillResize setDelegate:self]; since I set the delegate in Interface Builder, but I'm not sure why this works.

How does windowWillResize know that I'm referring to the main application window since I'm doing a completely new windowWillResize = [[NSWindow alloc] init];

I have a feeling that I am completely doing this wrong. Could someone point me in the right direction? Thanks!

3

3 Answers

3
votes

Indeed, you don't need to create a NSWindow *windowWilResize since a newly created Cocoa app already has a main window. You don't need to implement an -init method either.

You only need to set you appController as a delegate of your main window in Interface Builder and to implement the -windowWillResize: method in your appController.

If you are familiar with french language, you can take a look at a blog entry I have written on this subject: Délégation en Cocoa.

2
votes

You're leaking an instance of NSWindow. In -init you create an NSWindow instance. However, that is not used because when the NIB loads, it sets up all the connections that you specified in Interface Builder and you start using the window from the NIB instead. Do not create a window object in code - Interface Builder does it for you! :-)

In fact, it's not quite "instead"; your app controller is now the delegate for both NSWindow instances - the one that comes from the NIB and the one you instantiated in -init. However as the in-code NSWindow is never used anywhere else, it's still redundant and should be removed.

1
votes

If you just want to maintain the aspect ratio of the window you can use either of these two NSWindow methods:

  • setAspectRatio:(NSSize)
  • setContentAspectRatio:(NSSize)

The first method locks the entire window size, including the title bar. The second one just the content. You can call this method during the initialization of your window inside the delegate (for example: -applicationDidFinishLaunching)