Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage multiple windows in Cocoa apps with Interface Builder

I have this application with 3 classes: AppController, Profile, ProfileBuilder. I also need 3 windows: one for each class. I tried keeping all 3 as subclasses of NSObject and applying initWithNibName to an NSWindowController class WindowController variable but when I tried outputting some values on each window it wouldn't work, and also the window resulted as null using NSLog. I was wondering what was the best way to manage multiple windows, perhaps all from a same class like an AppWindowsController involving as least as possible specific code in the other classes, and keeping, if possible, the other classes as subclasses of NSObject and not NSWindowController. So if there is, maybe a way to control the behavior of the windows remotely, adding as least as possible code inside the specific classes, just to keep them as clear as possible and uniquely focused on their content. Thanks, hope I made myself clear, I'm actually pretty new to the Cocoa framework.

like image 431
BigCola Avatar asked Feb 20 '23 00:02

BigCola


2 Answers

You should be able to load the nib files with your windows in an init method for your different classes. For example, in Profile, you could do something like this:

-(id)init {
    if (self = [super init]) {
        NSArray *array;
        BOOL success = [[NSBundle mainBundle] loadNibNamed:@"ProfileWindow" owner: self topLevelObjects:&array];
        if (success) {
            for (id obj in array) {
                if ([obj isKindOfClass:[NSWindow class]]) {
                    self.profileWindow = obj;
                }
            }
            [self.profileWindow makeKeyAndOrderFront:self];
        }
    }
    return self;
}

profileWindow is a property (typed as strong). In the xib file, I set the File's Owner to Profile.

like image 77
rdelmar Avatar answered Feb 27 '23 10:02

rdelmar


I just like to improve the solution of rdelmar.

You don't need to iterate over the array to find the NSWindow class. If you define profileWindow as an outlet and connect it in the IB, the call

[[NSBundle mainBundle] loadNibNamed:@"ProfileWindow" owner:self topLevelObjects:&array];

will assign the window object to your outlet, the array stuff is not required. The key here is the owner object which act as interface. In the IB you can define the class type of the owner and if so, see its outlets.

like image 31
Stephan Avatar answered Feb 27 '23 11:02

Stephan