IOS个人开发ios框架我的ios进阶

iOS数据存储

2015-12-15  本文已影响658人  芝麻绿豆

iOS数据存储方式

应用沙盒

结构:

偏好设置

 if (json != nil) {
// 存储
 [[NSUserDefaults standardUserDefaults] setObject:json forKey:YANForumTitles];
 } else{
// 读取
 forum.titles = [YANTagTitle mj_objectArrayWithKeyValuesArray:[[NSUserDefaults standardUserDefaults]objectForKey:YANForumTitles]];
  }

写入式(plist-XML属性列表归档)

    // 系统路径
    NSString *DocuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 拼接文件路径
    NSString *path = [DocuPath stringByAppendingPathComponent:@"liuyan.plist"];
    // 写入
    [json writeToFile:path atomically:YES];
    // 读取并转化为模型
    forum.titles=[YANTagTitle mj_objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:path]];

归档(NSKeyedArchiver)

    // 系统路径
    NSString *DocuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 拼接文件路径
    NSString *path = [DocuPath stringByAppendingPathComponent:@"titles.liuyan"];
    // 写入
    [NSKeyedArchiver archiveRootObject:forum.titles toFile:path];
    // 读取
    for (int i = 0; i < forum.titles.count; i++) {
            YANTagTitle *title=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    }
   - (void)encodeWithCoder:(NSCoder *)aCoder
   {
       [aCoder encodeInteger:self.ID forKey:@"ID"];
       [aCoder encodeObject:self.n forKey:@"n"];

  }

读取文件时执行:- (instancetype)initWithCoder:(NSCoder *)aDecoder;

  - (instancetype)initWithCoder:(NSCoder *)aDecoder{
    //注意:在构造方法中需要先初始化父类的方法
       if (self=[super init]) {
           self.ID=[aDecoder decodeIntegerForKey:@"ID"];
           self.n=[aDecoder decodeObjectForKey:@"n"];
       }
    return self;  
}

SQList3

CoreData

上一篇 下一篇

猜你喜欢

热点阅读