您的位置:首页 > 移动开发 > IOS开发

iOS数据持久化 归档 plist文件

2016-06-07 14:40 260 查看
一般我们工程基本需要做数据持久化的要求,以减少流量的损失和用户没网的体验

下面介绍三种数据持久化的方法

第二种:归档

创建一个类   并且遵守<NSCoding>这个协议

@property(nonatomic,copy)NSString *name;

@property(nonatomic,assign)int age;

@property(nonatomic,assign)double height;
写三个要保存的属性

-(void)encodeWithCoder:(NSCoder *)aCoder   当将一个自定义对象保存到文件的时候就会调用该方法

{

   [aCoder encodeObject:self.name forKey:@"name"];

   [aCoder encodeInteger:self.age forKey:@"age"];

   [aCoder encodeDouble:self.height forKey:@"height"];

}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{    当从文件中读取一个对象的时候就会调用该方法

    self = [super init];

    if (self) {

        self.name = [aDecoder decodeObjectForKey:@"name"];

        self.age = [aDecoder decodeIntForKey:@"age"];

        self.height = [aDecoder decodeDoubleForKey:@"height"];

    }

    return self;

}

Student *stu = [Student new];   初始化并赋值

    stu.name = @"haha";

    stu.age = 223232;

    stu.height = 34234.532;

    stu.weight = 34300002;

NSString *sysPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];获取文件路径并将文件的对象保存到文件中

    NSString *path = [sysPath stringByAppendingPathComponent:@"student.lh"];

    NSLog(@"%@",path);

    [NSKeyedArchiver archiveRootObject:stu toFile:path];

读取数据

NSString *sysPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    NSString *path = [sysPath stringByAppendingPathComponent:@"student.lh"];

    Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    NSMutableArray *array = [@[stu.name,@(stu.age),@(stu.height),@(stu.weight)]mutableCopy];

    NSLog(@"%@",array);

第二种:plist文件保存

//获得路径并保存

    NSString *sysString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];

    NSString *path = [sysString stringByAppendingPathComponent:@"text.plist"];

    NSLog(@"%@",path);

    

    NSDictionary *dic1 = @{@"1":@"yangang",@"2":@"dingwei",@"3":@"zengjianxiong"};

    

    NSMutableDictionary *dic2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"dsfsd",@"name",@"6",@"age",@"girl",@"sex",nil];

    

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    [dic setObject:dic1 forKey:@"one"];

    [dic setObject:dic2 forKey:@"two"];

    [dic writeToFile:path atomically:YES];

//读取数据

    NSString *sysString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];

    NSString *path = [sysString stringByAppendingPathComponent:@"text.plist"];

    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithContentsOfFile:path];

    NSLog(@"%@",data);

第三种:单例保存

 [[NSUserDefaults standardUserDefaults]setObject:@"123" forKey:@"name"];//保存

 NSString *string = [[NSUserDefaults standardUserDefaults]objectForKey:@"name"];//读取
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息