这里我总结了一下数据的存储方式,一是保存在沙盒里创建文件,再把数据写到文件中,二是保存到plist中,三是保存到数据库中.
1.保存到文件中需要借助NSKeyedArchiver和NSKeyedUnArchiver
保存数据: NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *path = [pathsobjectAtIndex:0];
NSMutableData *data =[[NSMutableData alloc] init];
NSKeyedArchiver*archiver = [[NSKeyedArchiver alloc]
initForWritingWithMutableData:data];
[archiver encodeObject:_filleText.text forKey:@"ty"];
[archiver finishEncoding];
[data writeToFile:[path stringByAppendingPathComponent:@"test"]
atomically:YES];
[archiver release];
[data release];
获取数据:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [pathsobjectAtIndex:0];
NSMutableData *data =[[NSMutableData alloc] initWithContentsOfFile:
[path stringByAppendingPathComponent:@"test"]];
NSKeyedUnarchiver *unarchiver =[[NSKeyedUnarchiver alloc]
initForReadingWithData:data];
NSObject*ret = [[unarchiverdecodeObjectForKey:@"ty"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
也可以写成这样只不过前一种进行了序列化:
保存:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [pathsobjectAtIndex:0];
[NSKeyedArchiver archiveRootObject:_filleText.text toFile:[pathstringByAppendingPathComponent:@"test"]];
获取:
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [pathsobjectAtIndex:0];
NSString* str=[NSKeyedUnarchiver unarchiveObjectWithFile:[pathstringByAppendingPathComponent:@"test"]];
2.保存到plist文件中分为两种一种是保存在系统自带的plist中,另一种是保存在自已创建的plist文件中
保存到系统自带的plist
保存:
[[NSUserDefaults standardUserDefaults] setObject:_filleText.textforKey:@"save"];
[[NSUserDefaults standardUserDefaults]synchronize];
获取数据:
NSString*str=[[NSUserDefaults standardUserDefaults] objectForKey:@"save"];
保存到自已创的plist中
保存:
NSMutableDictionary* dict=[NSMutableDictionarydictionaryWithObjectsAndKeys:@"chen",@"sex",@"liang",@"name",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docPath = [pathsobjectAtIndex:0];
NSString *myFile = [docPath stringByAppendingPathComponent:@"user.plist"];
[dict writeToFile:myFile atomically:YES];
获取数据:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docPath = [paths objectAtIndex:0];
NSString *myFile = [docPath stringByAppendingPathComponent:@"user.plist"];
NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:myFile];
不过我写着写着,觉得第一种和第二种都差不多,基本上都可以归类为保存数据库到文件中,不同的就是保存到plist中可以打开看到里面的数据,第一种看不到,所以更安全些。3.保存数据到数据库里,一般分为两种一种是ios自带的数据库coredata,另一种是sqllite,我想说的是因为sqllite好多和c关联,如果对c不是很熟悉的话,建议用FMDataBase这个第三方库,它是对sqllite的封装,很好用,对于数据库这块下次再写
有什么问题请大家多指教