iOS 数据存储的常用方式

iOS 数据存储的常用方式_第1张图片
应用沙盒.png
iOS 数据存储的常用方式_第2张图片
沙盒机构分析.png
  • XML属性列表(plist)归档
  • Preference(偏好设置)
  • NSKeyedArchiver 归档 (NSCoding)
  • SQLite3
  • Core Data

一、plist存储

  • 写入
//第一个参数:搜索的目录
//第二个参数:搜索的范围
//第三个参数:是否展开路径(在ios当中识别~)
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSLog(@"%@",path);
//stringByAppendingPathComponent拼接一个文件路径.自动加一个(/)
NSString *filePath = [path stringByAppendingPathComponent:@"data.plist"];
NSLog(@"%@",filePath);
//把数组保存到沙盒
NSArray *dataArray =  @[@"xmg",@10];
//路径是沙盒路径.
[dataArray writeToFile:filePath atomically:YES];
  • 注意: 在plist文件当中是不能够保存自定义的对象

  • 读取

NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [path stringByAppendingPathComponent:@"data.plist"];
NSArray *dataArray = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"%@",dataArray);

二、偏好设置
NSUserDefaults它保存也是一个plist.

一些应用都支持偏好设置,比如保存用户名,密码,字体大小等设置,可以通过NSUserDefaults来存取偏好设置。比如,保存用户名,字体大小,是否自动登录。

  • 存储
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"xmg" forKey:@"name"];
[defaults setInteger:10 forKey:@"age"];
//立马写入到文件当中
[defaults synchronize];
  • 读取
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:@"name"];
NSLog(@"name ===%@",name);
NSInteger age = [defaults integerForKey:@"age"];
NSLog(@"%ld",age);

三、NSKeyedArchiver 归档 (NSCoding)

  • 创建对象类
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, strong) Dog *dog;

//在保存对象时告诉要保存当前对象哪些属性.
-(void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeObject:self.dog forKey:@"dog"];
    
}

//当解析一个文件的时候调用.(告诉当前要解析文件当中哪些属性.)
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    //当只有遵守了NSCoding协议时,才有[super initWithCoder]
    if (self = [super init]) {
        
       self.name = [aDecoder decodeObjectForKey:@"name"];
       self.age = [aDecoder decodeIntForKey:@"age"];
       self.dog = [aDecoder decodeObjectForKey:@"dog"];
    }
    return self;
}
  • 存储
Person *per =  [[Person alloc] init];
per.name = @"xmg";
per.age = 10;

//获取沙盒目录
NSString *tempPath =  NSTemporaryDirectory();
NSString *filePath = [tempPath stringByAppendingPathComponent:@"Person.data"];
NSLog(@"%@",tempPath);
    
//归档 archiveRootObject会调用encodeWithCoder:
[NSKeyedArchiver archiveRootObject:per toFile:filePath];
  • 读取
//获取沙盒目录
NSString *tempPath =  NSTemporaryDirectory();
NSString *filePath = [tempPath stringByAppendingPathComponent:@"Person.data"];
//unarchiveObjectWithFile会调用initWithCoder
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@---%@",per.name,per.dog.name);

你可能感兴趣的:(iOS 数据存储的常用方式)