第13章 User Defaults

这一章主要讲解程序的默认配置。每个应用程序都有它的默认配置。这些配置包括窗口的颜色,文档的属性等信息。默认配置一般存储在~/document/程序.plist文件里。本章接上一章的例子,当用户通过菜单打开preference窗口后,修改RaiseMan程序的属性,如何将用户的设置保存到默认配置文件里。以及当下一次打开程序时,如何从默认配置中提取信息。

整个过程分为三步。1.注册默认配置。2.存储和提取默认配置。3.使用默认配置改变程序行为


1.注册默认配置

+ (void)initialize
{
// Create a dictionary
NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];

// Archive the color object
NSData *colorAsData = [NSKeyedArchiver archivedDataWithRootObject:[NSColor yellowColor]];

// Put defaults in the dictionary
[defaultValues setObject:colorAsData forKey:BNRTableBgColorKey];
[defaultValues setObject:[NSNumber numberWithBool:YES] forKey:BNREmptyDocKey];

// Register the dictionary of defaults
[[NSUserDefaults standardUserDefaults] registerDefaults: defaultValues];
NSLog(@"registered defaults: %@", defaultValues);
}

2.更改和提取默认配置

- (IBAction)changeBackgroundColor: (id)sender
{
NSColor *color = [colorWell color];
NSData *colorAsData = [NSKeyedArchiver archivedDataWithRootObject:color];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:colorAsData forKey:BNRTableBgColorKey];
}

- (IBAction)changeNewEmptyDoc: (id)sender
{
int state = [checkbox state];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:state forKey:BNREmptyDocKey];
}

- (NSColor *)tableBgColor
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *colorAsData = [defaults objectForKey:BNRTableBgColorKey];
return [NSKeyedUnarchiver unarchiveObjectWithData:colorAsData];
}

- (BOOL)emptyDoc
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
return [defaults boolForKey:BNREmptyDocKey];
}

3.使用默认属性改变程序行为。
在delegate函数中,使用更改后的默认配置,改变窗口的属性。

- (void)windowControllerDidLoadNib: (NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *colorAsData;
colorAsData = [defaults objectForKey:BNRTableBgColorKey];
[tableView setBackgroundColor:[NSKeyedUnarchiver unarchiveObjectWithData:colorAsData]];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值