只要应用程序正在运行,我需要在 2 秒内更改一次状态图标,我认为就我而言,我必须在单独的线程中进行。
这是我的场景。
我在 MainMenu.nib 中初始化了 2 个 NSObject。其中之一是主控制器 AppDelegate 和另一个 ChangeStatusBar 来更改图标。我的 AppDeligate 中有一个 IBOutlet 指向 ChangeStatusBar 对象。从 AppDeligate 我正在调用 ChangeStatusBar 的一种方法,该方法使用 performSelectorInBackground 和运行循环来实现这一点。这是行不通的。我更改图标的方法被调用,但在 AppDeligate 等待期间图像没有改变。我的 Appdeligate 可以继续无条件等待,即使在这种情况下我也希望更改 StatusItem 图像。例如:假设您在 AppDeligate 中有 scanf,或者您正在调用一个可以在总和时间后返回的 API。提前致谢。这是我的代码。
// AppDelegate.m
-(void)applicationDidFinishLaunching:(NSNotification*)notification
{
[statusItem initStatusItem:true]; //StatusItem is the IBOutlet to ChangeStatusBar object
}
//ChangeStatusBar.m
-(void)initStatusItem:(BOOL) flag
{
statusItem = [[[NSStatusBar systemStatusBar]
statusItemWithLength:NSVariableStatusItemLength]retain] ;
[statusItem setMenu:statusMenu];
[statusItem setImage:[NSImage imageNamed:@"lk0.png"]];
[self performSelectorInBackground:@selector(timerStart) withObject:nil];
}
-(void) timerStart
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(changeImages)
userInfo:nil repeats:YES] retain];
[runLoop run];
[pool release];
}
///Change image here
-(void)changeImages
{
[statusItem setImage:[NSImage imageNamed:[NSString stringWithFormat:@"lk%d.png",NoImages]]];`
}