David David - 5 months ago 20
Objective-C Question

NSFontManager selectedFont returning null

Okay so I've checked all over S.O. and all over Google and I can't find what is wrong with my code:

- (IBAction)selectFont:(id)sender
{
NSFontManager *fontManager = [NSFontManager sharedFontManager];
[fontManager setDelegate:self];
[fontManager setTarget:self];

NSFontPanel *fontPanel = [fontManager fontPanel:YES];
[fontPanel makeKeyAndOrderFront:sender];
}

- (void)changeFont:(id)sender
{
NSFontManager *fontManager = [NSFontManager sharedFontManager];
font = [fontManager selectedFont];
NSLog(@"%@",[fontManager selectedFont]);
}


The font panel pops up, but when I select a font, the console returns
(null)
for the selected font of the Font Manager. Anyone know what I'm missing?

Thanks

Answer

Apple's Documentation says that using selectedFont in changeFont: could result in unexpected behavior and "The use of selectedFont from within changeFont: is strongly discouraged." The appropriate way to get a font from NSFontPanel is to ask NSFontManager to convert the current font into the selected font. Here is an example application that properly uses NSFontPanel:

@interface AppDelegate : NSObject <NSApplicationDelegate>{
    NSFont *font;
}

- (IBAction)selectFont:(id)sender;

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    font = [NSFont boldSystemFontOfSize:12];
}

- (IBAction)selectFont:(id)sender
{
    NSFontManager *fontManager = [NSFontManager sharedFontManager];
    [fontManager setDelegate:self];
    [fontManager setTarget:self];
    [fontManager orderFrontFontPanel:self];
}

- (void)changeFont:(id)sender
{
    font = [sender convertFont:font];
    NSLog(@"%@", font);
}

I've removed bits and pieces of the code that aren't relevant to your problem (such as IBOutlets to NSButtons and the NSWindow).
Please note this example uses ARC.

Another thing that is important to know is that the argument to convertFont: needs to be a valid NSFont instance. Otherwise, convertFont: will return nil even though a font has been selected in the NSFontPanel. For this reason, it's important to initialize the NSFont *font instance variable to an valid NSFont instance.

Comments