用NSArchiver和NSUnarchiver保存用户数据至文件

用NSArchiver和NSUnarchiver保存用户数据至文件


最近学习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/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值