Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create and open an NSWindow with ARC on Lion 10.7

I can't figure out how to allocate and open a new NSWindow without nib.

NSRect frame = NSMakeRect(100, 100, 200, 200);
NSUInteger styleMask =    NSBorderlessWindowMask;
NSRect rect = [NSWindow contentRectForFrameRect:frame styleMask:styleMask];
NSWindow * window =  [[NSWindow alloc] initWithContentRect:rect styleMask:styleMask backing: NSBackingStoreBuffered    defer:false];
[window setBackgroundColor:[NSColor blueColor]];
[window makeKeyAndOrderFront: window];

The code above is taken from this thread How do I create a Cocoa window programmatically?

like image 490
kilianc Avatar asked Aug 25 '11 23:08

kilianc


1 Answers

If you're using ARC, then unless you have a strong reference to the window, it will be released immediately after the last statement that references it.

ARC changes the way you need to think about objects, from a retain/release model to an ownership model. If nothing owns your window variable, it will go away.

There are several ways to take ownership of the window. You can set the window as either an instance variable or as a property in your class using the strong keyword, or you can use the __strong qualifier when you declare the variable in your code.

There is a lot more information about ARC at the LLVM compiler site.

like image 75
Rob Keniger Avatar answered Sep 27 '22 20:09

Rob Keniger