码迷,mamicode.com
首页 > 移动开发 > 详细

IOS数据存储之归档(NSKeyedArchiver)/解档(NSKeyedUnarchiver)

时间:2016-05-11 12:50:08      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

前言:

     前天学习了NSUserDefaults,我们知道NSUserDefaults不能保存自定义对象,所以我们今天来认识一下归档和解档。我们先来回顾一下JAVA是怎么实现保存一个自定义对象的!首先一个自定义对象必须实现Serializable接口,然后把一个对象序列化成二进制数据写入一个byte[]数据或者文件,反之则是从一个二进制数据或者文件中读取二进制数据反序列化成对象,所以我认为ios的归档解档其实就是类似JAVA序列化反序列化的过程,下面写个程序来尝试一下。

先测试下基础类型:

 //归档
    NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    //字符串数据
    NSString * string =@"who is lcj?";
    NSString *filename = [Path stringByAppendingPathComponent:@"testString"];
    [NSKeyedArchiver archiveRootObject:string toFile:filename];
    NSString *string1=[NSKeyedUnarchiver unarchiveObjectWithFile:filename];
    NSLog(@"testString---%@",string1);

    //集合数组
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"who", @"islcj", nil];
    filename = [Path stringByAppendingPathComponent:@"testArray"];
    [NSKeyedArchiver archiveRootObject:array toFile:filename];
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
    NSLog(@"testArray---%@",arr);
    
    //字典保存
    filename = [Path stringByAppendingPathComponent:@"testNSDictionary"];
    NSDictionary *dictionary=[NSDictionary dictionaryWithObject:@"whoislcj" forKey:@"name"];
    [NSKeyedArchiver archiveRootObject:dictionary toFile:filename];
    NSDictionary *dictionary1=[NSKeyedUnarchiver unarchiveObjectWithFile: filename];
    NSLog(@"dictionary---%@",dictionary1);
    

上面已经说了JAVA要想实现序列化反序列化必须实现Serializable接口,那么iOS呢?iOS需要实现NSCoding协议,

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCoding>

@property (nonatomic,strong)NSString *name;

@end

Person.m

#import "Person.h"

@implementation Person

#pragma mark - NSCoding Delegate

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self.name = [aDecoder decodeObjectForKey:@"name"];
    return self;
}

@end

具体实现:

    //自定义对象类型
    Person *person=[[Person alloc]init];
    person.name=@"whoislcj";
    filename = [Path stringByAppendingPathComponent:@"testObject"];
    [NSKeyedArchiver archiveRootObject:person toFile:filename];
    Person *tempPerson = [NSKeyedUnarchiver unarchiveObjectWithFile: filename];
    NSLog(@"tempPerson:%@",tempPerson.name);

归档如何删除

      //删除归档文件
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager isDeletableFileAtPath:filename]) {
            [defaultManager removeItemAtPath:filename error:nil];
        }

 

缺点:归档的形式来保存数据,只能一次性归档保存以及一次性解压。所以只能针对小量数据,而且对数据操作比较笨拙,即如果想改动数据的某一小部分,还是需要解压整个数据或者归档整个数据。

IOS数据存储之归档(NSKeyedArchiver)/解档(NSKeyedUnarchiver)

标签:

原文地址:http://www.cnblogs.com/whoislcj/p/5481123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!