How to get display name from NSScreen Jan 14, 2011
While working on Wallpapery I needed to get a given screens display name. There is no “displayName” method on NSScreen so I added a category to provide this functionality. Seems like others are looking for this too so I’m posting my code below.
NSScreen+DisplayName.h
#import <Cocoa/Cocoa.h>
@interface NSScreen (DisplayName)
- (NSString *)displayName;
@end
NSScreen+DisplayName.m
#import <IOKit/graphics/IOGraphicsLib.h>
#import "NSScreen+DisplayName.h"
@implementation NSScreen (DisplayName)
- (NSString *)displayName {
NSString *screenName = nil;
io_service_t framebuffer = CGDisplayIOServicePort([[[self deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue]);
NSDictionary *deviceInfo = (NSDictionary *)IODisplayCreateInfoDictionary(framebuffer, kIODisplayOnlyPreferredName);
NSDictionary *localizedNames = [deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
if ([localizedNames count] > 0) {
screenName = [[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] retain];
}
else {
screenName = @"Unknown";
}
[deviceInfo release];
return [screenName autorelease];
}
@end
You need to include the IOKit framework in your project.
Enjoy.