views:

311

answers:

3

I want to get the dimensions of the main screen, so I use this snippet:

NSLog(@"mainScreen frame = %@", [[NSScreen mainScreen] visibleFrame]);

It's printing

mainScreen frame = (null)

Earlier it was printing the expected dimensions of my main monitor.

What are some possible causes of this?

+7  A: 

Hi Steve - the problem here is you're running up against one of the relatively few non-objects in Objective-C Cocoa programming.

The result of "visibleFrame" is an NSRect structure, not an object. To get it to display meaningfully in the NSLog line, you have to do something like this:

NSString* frameAsString = NSStringFromRect([[NSScreen mainScreen] visibleFrame]);
NSLog(@"mainScreen frame = %@", frameAsString);

There are helper functions for converting many of these structure objects to strings and back, e.g. NSStringFromPoint, NSStringFromRange, etc.

danielpunkass
Ah thanks, I feel pretty silly now I realise what I did. I'm still a beginner at Objective-C.
Steve McLeod
It takes a while before all the exceptions to the rules sink in and become second nature. You'll get there!
danielpunkass
+1  A: 

-visibleFrame returns an NSRect struct, while you're using a string specifier for an object. You need to use the NSStringFromRect() function (I believe it's called) to turn the rect into a string object for NSLog().

Marc Charbonneau
+2  A: 

The documentation on this needs to be read carefully. The "main screen", as Apple defines it, is not necessarily the screen with the menu bar. The "main screen" is the screen that is receiving keyboard events. If, for some reason the OS thinks that no screens have the keyboard focus then I could understand why mainScreen would return NULL.

To get the screen with the menu bar (And origin at (0,0)) you need to use:

[[NSScreen screens] objectAtIndex:0]

I've never seen this return NULL, although I won't say that it can't happen.

Mark Thalman
It's not even necessarily the one receiving keyboard events. It's the screen with the main window on it. (The window receiving keyboard events is the key window, and may be separate from the main window—for example, it may be a floating panel.)
Peter Hosey
I would think that a floating window with the keyboard focus would make that the main screen, even if the main window is on screen 0 from the screens array.I was just pointing out that the main screen may not be what I had originally assumed it was until I read the docs. Others may make the same mistake. My code that made this mistake is burned onto thousands of CDs around the world.
Mark Thalman