数据存储的常见方式

第一种保存方式:NSKeyedArchiver

代码很简单就不多解释了直接上代码:    //=================NSKeyedArchiver========================
NSString *saveStr1 = @"我是";
NSString *saveStr2 = @"数据";
NSArray *array = [NSArray arrayWithObjects:saveStr1, saveStr2, nil];
//----Save
//这一句是将路径和文件名合成文件完整路径
NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [Path stringByAppendingPathComponent:@"saveDatatest"];
[NSKeyedArchiver archiveRootObject:array toFile:filename];
//用于测试是否已经保存了数据
saveStr1 = @"hhhhhhiiii";
saveStr2 =@"mmmmmmiiii";
//----Load
array = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
saveStr1 = [array objectAtIndex:0];
saveStr2 = [array objectAtIndex:1];
CCLOG(@"str:%@",saveStr1);
CCLOG(@"astr:%@",saveStr2);


 第二种保存方式:NSUserDefaults

代码很简单就不多解释了直接上代码:=================NSUserDefaults========================
NSString *saveStr1 = @"我是";
NSString *saveStr2 = @"数据";
NSArray *array = [NSArray arrayWithObjects:saveStr1, saveStr2, nil];
//Save
NSUserDefaults *saveDefaults = [NSUserDefaults standardUserDefaults];
[saveDefaults setObject:array forKey:@"SaveKey"];
//用于测试是否已经保存了数据
saveStr1 = @"hhhhhhiiii";
saveStr2 =@"mmmmmmiiii";
//---Load
array = [saveDefaults objectForKey:@"SaveKey"];
saveStr1 = [array objectAtIndex:0];
saveStr2 = [array objectAtIndex:1];
CCLOG(@"str:%@",saveStr1);
CCLOG(@"astr:%@",saveStr2);


第三种保存方式:Write写入方式

代码很简单就不多解释了直接上代码://=================Write写入方式========================
NSString *saveStr1 = @"我是";
NSString *saveStr2 = @"数据";
NSArray *array = [NSArray arrayWithObjects:saveStr1, saveStr2, nil];
//----Save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
    NSLog(@"没找到");
}
NSMutableArray *saveDataArray=nil;
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"Savedatas.plist"];
[[NSArray arrayWithObjects:array,nil] writeToFile:appFile atomically:NO];
//用于测试是否已经保存了数据
saveStr1 = @"hhhhhhiiii";
saveStr2 =@"mmmmmmiiii";
//----Load
if([[NSFileManager defaultManager] fileExistsAtPath:appFile]){
    saveDataArray = [NSMutableArray arrayWithContentsOfFile:appFile];
} else{
    saveDataArray = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Savedatas" ofType:@"plist"]];
}
NSArray *strArray = [saveDataArray objectAtIndex:0];
saveStr1 = [strArray objectAtIndex:0];
saveStr2 = [strArray objectAtIndex:1];
CCLOG(@"str:%@",saveStr1);
CCLOG(@"astr:%@",saveStr2);


 不论哪种形式代码都很容易理解,那么以上三种保存方式代码中都带有如下两行代码;
    saveStr1 = @"hhhhhhiiii";
saveStr2 =@"mmmmmmiiii";
posted @ 2012-04-24 19:40  高笑228  阅读(260)  评论(0编辑  收藏  举报