Under what circumstances would [[NSScreen mainScre

2020-07-27 03:53发布

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?

4条回答
来,给爷笑一个
2楼-- · 2020-07-27 04:29

-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().

查看更多
Animai°情兽
3楼-- · 2020-07-27 04:44

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.

查看更多
贪生不怕死
4楼-- · 2020-07-27 04:50

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);
查看更多
疯言疯语
5楼-- · 2020-07-27 04:51

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.

查看更多
登录 后发表回答