Reputation: 52468
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?
Upvotes: 2
Views: 2262
Reputation: 488
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:
NSLog(@"screen is %.2f wide and %.2f high", [[[NSScreen screens]
objectAtIndex:0] visibleFrame].size.width, [[[NSScreen screens]
objectAtIndex:0] visibleFrame].size.height);
Upvotes: 0
Reputation: 6128
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.
Upvotes: 2
Reputation: 17587
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.
Upvotes: 9
Reputation: 40515
-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().
Upvotes: 1