【iOS】数据持久化

2015-11-03  本文已影响0人  cod_mm

在iOS开发中我们常常需要做数据存储,这里主要说的时以下几种本地数据存储的方式。

NSUserDefaults
属性列表: 集合对象可以读写到属性列表中
对象归档:对象可以保存到归档文件中
SQLite数据库:开源嵌入式关系型数据库
FMDB:

NSUserDefaults

NSUserDefaults适合存储轻量级的本地数据,比如用户的信息,登录状态等数据。
NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSDate,NSArray,NSDictionary,BOOL类型

// 存
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"iOS开发者" forKey:@"name"];
[defaults synchronize];

// 取
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSString *name = [userDefault objectForKey:@"name"];

属性列表

属性列表文件是一种XML文件,Foundation框架中的数组和字典等都可以于属性列表文件相互转换。

 // 存储路径 
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"array.plist"];

// 写数据
NSArray *array = @[@"test1", @"test2", @"test3"];
[array writeToFile:path atomically:YES];

// 读数据
NSArray *getArray = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(@"---读取的数据---%@", getArray); 
// 存储路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"dict.plist"];

// 写数据
NSDictionary *dict = @{@"a":@"test1", @"b":@"test2", @"c":@"test3"};
[dict writeToFile:path atomically:YES];

// 读数据
NSDictionary *getDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSLog(@"---读取的数据---%@", getDict);

对象归档

对象归档是一种序列化方式。存储即将归档对象序列化位一个文件进行持久化,读取是通过反归档将持久化的数据恢复到对象中。
注意:可归档的对象必须实现NSCoding协议

自定义类实现NSCoding协议

  @interface Person : NSObject <NSCoding>
  @property(nonatomic, copy) NSString *name;
  @property(nonatomic, copy) NSString *sex;
  @property(nonatomic, assign) NSInteger age;
  @end 

  @implementation Person
  - (void)encodeWithCoder:(NSCoder *)aCoder {
      [aCoder encodeObject:self.name forKey:@"name"];
      [aCoder encodeObject:self.sex forKey:@"sex"];
      [aCoder encodeInteger:self.age forKey:@"age"];
  }
  - (instancetype)initWithCoder:(NSCoder *)aDecoder {
      if (!(self = [super init])) {
          return nil;
      }
      self.name = [aDecoder decodeObjectForKey:@"name"];
      self.sex = [aDecoder decodeObjectForKey:@"sex"];
      self.age = [aDecoder decodeIntegerForKey:@"age"];
      return self;
  }
  @end

归档/解档

Person *person = [[Person alloc] init];
person.name = @"iOS开发着";
person.sex = @"男";
person.age = 1000;    
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];

// 归档
[NSKeyedArchiver archiveRootObject:person toFile:file];

// 解档
Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
if (per) {
    NSLog(@"-------解归档---name----: %@", per.name);
    NSLog(@"-------解归档---sex----: %@", per.sex);
    NSLog(@"-------解归档---age----: %ld", per.age);
}

SQLite3

FMDB

上一篇 下一篇

猜你喜欢

热点阅读