1. IOS数据存储:
什么是沙盒: 与其他文件系统隔离,应用必须待在自己的沙河里面,不能互相访问
bundle 和 沙盒是分开的
*沙盒路径:
Documents :比较贵重数据,Itunes 会设备的时候会备份改目录
Library/Caches : 不会备份,存储体积大
Library/Preference: 保存偏好设置, 系统管理,会备份
tmp: 临时数据,不会备份,引用没有运行时候,系统可能清除该目录
*bundle路径:
xx.app
*Sqlite3 数据存储, Core Data: 对sqlite封装,面向对象
2. 数据存储Api:
// 获取Bundle 路径
NSString* path= [NSBundle mainBundle].bundlePath;
NSLog(@"path=%@",path);
// 获取 Documents 文件夹
//1. 获取沙盒路径
NSString* homeDir= NSHomeDirectory();
NSLog(@"沙盒:%@",homeDir);
// 2. 拼接字符串(方式1)
NSString* documentPath= [homeDir stringByAppendingString:@"/Documents"];
NSLog(@"documentPath=%@",documentPath);
// 方式2
documentPath= [homeDir stringByAppendingPathComponent:@"Documents"];
NSLog(@"方式2:%@",documentPath);
// 方式3
documentPath = [ NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask , YES) lastObject];
NSLog(@"方式3: %@",documentPath);
// 获取Libray/Caches 文件夹
NSString* libraryCache= [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"librayCache:%@",libraryCache);
//获取 tmp 文件夹
NSString* tempPath = NSTemporaryDirectory();
NSLog(@"tempPath:%@",tempPath);
// 偏好设置 Library/Preference
// 偏好设置,比如记住密码, 是否自动登录功能
NSUserDefaults* userDefault= [NSUserDefaults standardUserDefaults];
// 设置数据
[userDefault setBool:YES forKey:@"isAutologin"];
[userDefault setObject:@"jack" forKey:@"name"];
[userDefault setObject:@"123" forKey:@"pwd"];
// 立即存储
[userDefault synchronize];
NSLog(@"%@",NSHomeDirectory());
// 读取偏好设置
BOOL isAutoLogin = [userDefault boolForKey:@"isAutologin"];
NSString* name =[userDefault stringForKey:@"name"];
NSLog(@"%d---%@",isAutoLogin,name);
3. Documents/name.plist数据存储 , 类似Android Sp存储
// 数据写入
NSString* direPath = [NSHomeDirectory() stringByAppendingString:@"/Documents"];
NSString* filePath= [direPath stringByAppendingString:@"/name.plist"];
NSArray* array=@[@"A",@"B",@"C"];
NSLog(@"direPath:%@",filePath);
[array writeToFile:filePath atomically:YES];
// 数据读取
NSArray* readArray= [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"readArray:%@",readArray);
实体类存储plist中,归档,反归档
Person.h
#import "Person.h"
@interface Person()
@end
@implementation Person
// 归档 告诉系统要存储对象的那些属性
-(void)encodeWithCoder:(NSCoder *)coder{
[coder encodeObject:self.name forKey:@"name"];
}
// 反归档, 读取对象的那些属性
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
if(self = [super init]){
self.name = [coder decodeObjectForKey:@"name"];
}
return self;
}
@end
4. 存储 数据 写入、读取:
// 归档 存储数据
NSString* direPath = [NSHomeDirectory() stringByAppendingString:@"/Documents"];
NSString* filePath= [direPath stringByAppendingString:@"/name.plist"];
Person* person= [Person new];
person.name=@"xiaoming";
[NSKeyedArchiver archiveRootObject:person toFile:filePath];
NSLog(@"home:%@",NSHomeDirectory());
//反 归档 读取数据
person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"person.name:%@",person.name);