Xcode 3.2.2
Mac OS X 10.6.8
Cocoa Programming for Mac OS X (third edition)
Chapter 6: Helper objects
What happened to the forum software? I can't quote text/code anymore.
I'm trying to create a simple delegate for an NSWindow. The delegate implements this method:
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize;
I can get my delegate to work if I use Interface Builder to connect my app's main(and only) window to an instance of my object(which appears in the MainMenu.xib inspector in IB). However, I cannot get a delegate to work if I call setDelegate: on my app's main window. In the book, there is one example where they use setDelegate: to setup the delegate object. There is another example where they use IB to hook up the delegate. The only distinction I can detect between the two examples is that in the one that employs setDelegate:, the delegate-or is not a widget, and in the one that uses IB to make the connection, the delegate-or is a widget.
This is the code that I used to try and programmatically set up a delegate:
//AppController.h
#import
@interface AppController : NSObject {
IBOutlet NSWindow* window;
}
- (id)init;
@end
//AppController.m
#import "AppController.h"
#import "MyDelegate.h"
@implementation AppController
- (id)init
{
if (![super init]) {
return nil;
}
MyDelegate* aDelegate = [[MyDelegate alloc] init];
[window setDelegate:aDelegate];
return self;
}
@end
//MyDelegate.h
#import
@interface MyDelegate : NSObject
}
- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)frameSize;
@end
//MyDelegate.m
#import "MyDelegate.h"
@implementation MyDelegate
- (NSSize)windowWillResize:(NSWindow *)sender
toSize:(NSSize)frameSize
{
frameSize.height = 2 * frameSize.width;
return frameSize;
}
@end
In IB, I went into the Library, and I dragged an Object to the MainMenu.xib window/inspector, and I named it AppController. Then I dragged a connection from the AppController outlet named 'window' to the NSWindow. When I build&run my code, I can resize the window to any size--the window size is not constrained to a 2:1 ratio. That is not the result I expect: I expect the window size to maintain a 2:1 ration. If I set an object's delegate, then when the event occurs, the object should grab the delegate and use it to call the delegation methods; there is nothing more I should have to do in my code. What am I not understanding about cocoa delegates?
0 comments:
Post a Comment