最近学习Cocoa编程,装了Xcode 4.8的环境,参考《Cocoa入门 - 使用Objective-C》一书,里边很多方法都被丢弃或者替换。
边学习,边修改为最新代码,以便备份,以便参考!
P217 在Menu应用程序中天假编码和归档功能
-(IBAction)save:(id)sender
{
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setCanCreateDirectories:YES];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:@"~/Documents"]];
[savePanel setNameFieldStringValue:@"menu.items"]; //以上设置保存Panel的属性
//下面的过程打开保存文件框,然后用completionHandler中定义的函数处理保存文件的逻辑
[savePanel beginSheetModalForWindow:[table window] completionHandler:^(NSInteger result) {
if (result == NSOKButton)
{
[savePanel orderOut:self];
NSString *fileName = [[savePanel URL] path];
[NSArchiver archiveRootObject:items toFile:fileName];
}
}];
}
-(IBAction)load:(id)sender
{
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setTreatsFilePackagesAsDirectories:NO];
[openPanel setAllowsMultipleSelection:NO];
[openPanel setCanChooseDirectories:NO];
[openPanel setCanChooseFiles:YES]; // 以上的过程设置打开文件框的属性
//下面过程打开文件对话框,并且用completionHandler中定义的过程来处理打开文件逻辑
[openPanel beginSheetModalForWindow:[table window] completionHandler:^(NSInteger result) {
if (result == NSOKButton) {
NSMutableArray *array;
NSString *fileName = [[openPanel URL] path];
array = [NSUnarchiver unarchiveObjectWithFile:fileName];
[array retain];
[items release];
items = array;
[table reloadData];
}
}];
}
参考:http://yeeyaa.me/articles/2011/03/save-and-load-user-data-to-local-file-using-nsarchiver-and-nsunarchiver/