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?
-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().
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:
I've never seen this return NULL, although I won't say that it can't happen.
You're trying to log an object but the method isn't returning an object, it's returning a struct.
Although NSStringFromRect will help you with logging, it's likely you'll want the actual integers elsewhere.
You can accomplish both with:
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:
There are helper functions for converting many of these structure objects to strings and back, e.g. NSStringFromPoint, NSStringFromRange, etc.