I am making a simple mac app in which i want to switch windows.
I have two NSWindowController class MainWindow and DetailWindow
I am using this code :
MainWindow class:
//MainWindow.h
@class DetailWindow;
@interface MainWindow : NSWindowController{
IBOutlet NSButton *btn1;
DetailWindow *detailwindow;
}
@property (nonatomic, retain) IBOutlet NSButton *btn1;
- (IBAction)btn1Event:(id)sender;
//MainWindow.m
@implementation MainWindow
@synthesize btn1;
- (IBAction)btn1Event:(id)sender {
if (!detailwindow) {
detailwindow = [[DetailWindow alloc] initWithWindowNibName:@"DetailWindow"];
}
[detailwindow showWindow:self];
}
@end
DetailWindow Class:
//DetailWindow.h
@class MainWindow;
@interface DetailWindow : NSWindowController{
IBOutlet NSButton *backbtn;
MainWindow *mainwindow;
}
@property (nonatomic, retain) IBOutlet NSButton *backbtn;
- (IBAction)back:(id)sender;
//DetailWindow.m
@implementation DetailWindow
@synthesize backbtn;
- (IBAction)back:(id)sender {
if (!mainwindow) {
mainwindow = [[MainWindow alloc] initWithWindowNibName:@"MainWindow"];
}
[mainwindow showWindow:self];
}
@end
Now the problem is when i click backbtn on DetaiWindow it will open a new MainWindow.
So i have two MainWindow on screen.
I want just main window at front when i click backbtn.
Any help??
Thank you..!!
Your basic problem is that each window is assuming that it is its own job to create the other. Each has an ivar for the other, but there’s no external access to it — via a property or being an
IBOutletor anything else — so it always starts out asnil, and a new copy gets created instead of reusing the old one.There are any number of ways to get around this. Probably the easiest would be to create both windows in Interface Builder and link them up there, having made the ivars
IBOutlet. Then you know you never have to create them in code at all.However, purely on the basis of inertia, here’s an alternative that sticks closer to what you’ve got already. Note that I’ve assumed for simplicity that
mainWindowalways exists first. If not, you’ll have to duplicate the process the other way around.Untested, so usual caveats apply.