一. 路径的获取
1.Bundle路径: app的安装目录
NSString *bundlePath =[NSBundle mainBundle].bundlePath;
2.沙盒路径:app存储数据的
NSString *document =NSHomeDirectory();
》document
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject]
》library
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)lastObject];
》tmp
NSString *cachespath =[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
》caches
NSString *cachespath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory(), NSUserDomainMask, YES) lastObject];
二. 数据的三种存储方式
//1、获取沙盒documents 路径
NSString *path =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//2、拼接文件名
path = [pathstringByAppendingPathComponent:@"data.zzz"];
//1.writeTofile
[names writeToFile:pathatomically:YES];
//2.偏好设置存储
1.获取偏好设置对象
NSUserDefaults *defaul =[NSUserDefaults standardUserDefaults];
2.存储数据
[defaul setObject:@"小明"forKey:@"name"];
[defaul setInteger:100 forKey:@"money"];
[defaul setBool:NO forKey:@"youmeiyou"];
3.立即同步
[defaul synchronize];
//3.归档
[NSKeyedArchiverarchiveRootObject:p toFile:path];
解档
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
1.遵守NSCoding 协议
//"归档"只是存储数据的过程
//这是告诉系统对象的哪些属性需要存储,该如何存储;若该属性没写不会存储进去
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInt:self.girl forKey:@"girl"];
[aCoder encodeBool:self.sure forKey:@"sure"];
}
//"归档"只是读取数据的过程
//这是告诉系统取出的哪些数据赋值给对象的哪些属性,若该属性没写不会获取出来
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if(self= [super init]){
self.name = [aDecoder decodeObjectForKey:@"name"];
self.girl = [aDecoder decodeIntForKey:@"girl"];
self.sure = [aDecoder decodeBoolForKey:@"sure"];
}
return self;
}