1

我的代码分为两个主要实现:MenuController.m 和 AppController.m,每个都有头文件。

我有几个用户首选项,它们使用 NSUserDefaults 存储,并通过 NSMenuItems 进行更改,以便在启用时显示复选标记(使用setState: NSOffState)。我的设置只缺少一点——如果选项在首选项中打开,我需要应用程序在启动时为这些菜单项设置状态。但是,我知道在应用程序启动时设置某些内容的唯一方法是将它放在awakeFromNib方法中,并且它位于 AppController 中,并且无法访问在MenuController中实例化的 NSMenuItem。

我对 Objective-C 还很陌生,并且由于这个网站上有许多有用的教程和答案,我已经成功地走到了这一步,但现在我只是被难住了。

我尝试使用类和对象方法来更改设置,但失败了——我需要使用 NSMenuItems 的现有实例。 validateMenuItem看起来很有希望,但它只启用和禁用菜单并且不设置状态。

相关代码(我认为):

来自 MenuController.h:

@interface MenuController : NSMenu {
 IBOutlet NSMenu *optionsMenu;
 IBOutlet NSMenuItem *onTopItem;
 IBOutlet NSMenuItem *liveIconItem;
}

- (IBAction)menuLiveIconToggle:(id)pid;

来自 MenuController.m:(更改首选项和 setState 的方法效果很好)

- (IBAction)menuLiveIconToggle:(id)pid; {
 //NSLog(@"Live Icon Toggle");
 NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
 if ([standardUserDefaults boolForKey:@"LiveIcon"] == TRUE){
  [standardUserDefaults setBool:FALSE forKey:@"LiveIcon"];
  [liveIconItem setState: NSOffState];
 } else {
  [standardUserDefaults setBool:TRUE forKey:@"LiveIcon"];
  [liveIconItem setState: NSOnState];
 }
 [standardUserDefaults synchronize];
}

来自 AppController.m:(不起作用,但这是它的要点)

- (void) awakeFromNib{
 // Update menu items
 if ([standardUserDefaults boolForKey:@"LiveIcon"] == TRUE) {
  [liveIconItem setState: NSOnState];
 } else {
  [liveIconItem setState: NSOffState];
 }
}

谢谢你的帮助!

4

1 回答 1

3

There are several ways you could achieve this. First, you could simply move your awakeFromNib implementation into your MenuController class, where you have access to the outlets. awakeFromNib is not specific to the App Delegate, but available for all objects that are loaded from Nibs (as you have outlets in your MenuController, I assume that it is loaded from a Nib).

You could also implement validateMenuItem:, always return YES, but also set the state of the menu item that is given to you as the parameter.

Or, get rid of all the code and just use bindings in Interface Builder. You can bind the "value" (== state) of your menu item to the "Shared User Defaults Controller" and enter "LiveIcon" as the model key path. You can then delete all of the code you posted and it'll just work.

于 2011-01-13T04:56:08.830 回答