How to get display name from NSScreen

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 

@interface NSScreen (DisplayName)

- (NSString *)displayName;

@end

NSScreen+DisplayName.m

#import 
#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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.