这一章主要讲解程序的默认配置。每个应用程序都有它的默认配置。这些配置包括窗口的颜色,文档的属性等信息。默认配置一般存储在~/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]];
}