Andrew M
Andrew M

Reputation: 4288

NSWindow Disappears

I have this code set to run on my app launch:

    NSRect rect = NSMakeRect(0, 0, 200, 50); //The location of the window
    NSWindow *win = [[NSWindow alloc] initWithContentRect:rect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
    [win setOpaque:NO];

    [win setLevel:NSFloatingWindowLevel];
    //[win setBackgroundColor:[NSColor clearColor]];

    //or

    NSView *myView = [[NSView alloc] initWithFrame: NSMakeRect(0, 0, 200, 50)];
    NSButton *myButton = [[NSButton alloc] initWithFrame:NSMakeRect(10, 5, 180, 40)];

    [myView addSubview: myButton];
    [win setHidesOnDeactivate:NO];

    [win setContentView: myView];

    [win orderFront: nil];

It works as expected (displays a button in the bottom left hand corner of the screen) for about a second, then it disappears. Why is it disappearing? Memory management, or something else, and how do I fix it?

Upvotes: 1

Views: 1036

Answers (2)

bbum
bbum

Reputation: 162722

First, it is extremely odd to be building user interface without simply using Interface Builder. Can be done and there are a handful of reasons to do so, but they are pretty few and far between.

Next, that code, by itself, isn't enough to say what has gone wrong. Creating a UI programmatically begs a whole series of questions; gc or not? ... how is your run loop configured? ... do you have a properly configured app wrapper?

As Abizem said, the most obvious guess would be that you have GC enabled and you haven't rooted the window in some global variable somewhere, directly or indirectly. It "just works" in a standard Cocoa application because NSWindow instances are rooted via the Cocoa application infrastructure (the Windows menu, specifically).

Upvotes: 6

Abizern
Abizern

Reputation: 150755

Are you working with Garbage Collection?

Do you have an iVar that is holding on to win? It could be that it is being garbage collected out from under you.

Upvotes: 4

Related Questions