Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an NSMenuItem that I need to update to show a progress (like Time machine does with it's backup). The problem is that when I set a new title on that NSMenuItem and the title is not changing.

It is in fact changing when I close and reopen the menu, but I want to update it while the user is looking at it.

I also tried remove an item and re-inserting it with no result.

Any pointers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
594 views
Welcome To Ask or Share your Answers For Others

1 Answer

This actually works with no additional effort if your updating code runs in the run loop mode which is used during menu tracking. This is NSEventTrackingRunLoopMode, but you probably just want to use NSRunLoopCommonModes so the menu item title is correct when the menu is pulled down.

Here's a simple example of a menu item foo that counts the number of seconds since the app launched:

- (void)doStuff;
{
    static int i = 0;
    [foo setTitle:[NSString stringWithFormat:@"%d", ++i]];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
{
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                                [self methodSignatureForSelector:@selector(doStuff)]];
    [invocation setTarget:self];
    [invocation setSelector:@selector(doStuff)];
    [[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:1 invocation:invocation repeats:YES] forMode:NSRunLoopCommonModes];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...