NSKeyedArchive(存储自定义对象)

在viewController.m中:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ZWPerson *p = [[ZWPerson alloc] init];
    p.name = @"mc";
    p.age = 18;
    p.height = 1.88;
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject];
    NSString *doucument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
    //拼接路径
    NSString *path = [cache stringByAppendingPathComponent:@"abc.doc"];
    NSString *path1 = [doucument stringByAppendingPathComponent:@"/ce.doc"];
    //存储数据
    BOOL ar = [NSKeyedArchiver archiveRootObject:p toFile:path];
    BOOL ar1 = [NSKeyedArchiver archiveRootObject:p toFile:path1];
    NSLog(@"%d---%d",ar,ar1);
    //读取数据
    ZWPerson *p1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    ZWPerson *p2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path1];
    NSLog(@"%zd---%@",p1.age,p2.name);
}

新建ZWPerson类(继承自ViewController)

在ZWPerson.h中:

#import "ViewController.h"
@interface ZWPerson : ViewController
/** 名字 */
@property (strong, nonatomic)NSString *name;
/** 年龄 */
@property (assign, nonatomic)NSInteger age;
/** 身高 */
@property (assign, nonatomic)double height;
@end

在ZWPerson.m中:

#import "ZWPerson.h"
@interface ZWPerson ()
@end
@implementation ZWPerson
//存储的时候调用这个方法
- (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
{
    if (self = [super initWithCoder:aDecoder]) {.
        //获取对象的属性(根据实际需要获取数据)
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
        self.height = [aDecoder decodeDoubleForKey:@"height"];
    }
    return self;
}
@end

如果是继承自NSObject:则只需要更改initWithCoder中的if(self = super init)即可

注意:1、遵守NSCoding协议,并实现该协议中的两个方法。

     2、如果是继承,则子类一定要重写那两个方法。因为person的子类在存取的时候,会去子类中去找调用的方法,没找到那么它就去父类中找,所以最后保存和读取的时候新增加的属性会被忽略。需要先调用父类的方法,先初始化父类的,再初始化子类的。

     3、保存数据的文件的后缀名可以随意命名。

     4、通过plist保存的数据是直接显示的,不安全。通过归档方法保存的数据在文件中打开是乱码的,更安全。

 

posted @ 2016-07-05 16:17  潜意识  阅读(337)  评论(0编辑  收藏  举报