Data storage -NSKeyedArchiver (a)

Ios in development, the data stored in one of the ways is stored directly into an object file. An object directly to a file you want to use class is NSKeyedArchiver. To the objects stored in the file to read out the necessary use of another class NSKeyedUnarchiver. These two classes are paired, but the use of these two classes object is saved to a file or object to be analyzed are conditional from the file. NSCoding object must implement the agreement and to achieve an agreement in the method. Below to save the custom object class CZPerson learn how to use the above example to save or read two classes.

//
//  CZPerson.h
//
//  Created by pkxing on 14/12/8.
//  Copyright (c) 2014年 梦醒. All rights reserved.
//  自定义类必须实现NSCoding协议

#import <Foundation/Foundation.h>

@interface CZPerson : NSObject<NSCoding>
/**
 *  姓名
 */
@property(nonatomic,copy) NSString *name;

/**
 *  年龄
 */
@property(nonatomic,assign) int  age;

@end

//
//  CZPerson.m
//  Created by pkxing on 14/12/8.
//  Copyright (c) 2014年 梦醒. All rights reserved.
//

#import "CZPerson.h"

@implementation CZPerson

/**
 *  当保存对象到文件中的时候系统会调用这个方法
 *
 *  一般在这个方法中告诉系统如何保存对象的属性值
 */
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:_name forKey:@"name"];
    [encoder encodeInteger:_age forKey:@"age"];
}

/**
 *  当从文件中初始化一个对象的时候系统会调用这个方法
 *
 *  一般在这个方法中告诉系统如何解析对象的属性值
 *
 *  @return 初始化好的对象
 */
- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    if (self) {
        _name = [decoder decodeObjectForKey:@"name"];
        _age = [decoder decodeIntegerForKey:@"age"];
    }
    return self;
}
@end

You can then save the image as the following objects to a file or read from a file. Remember: what type of object is stored, what type of object is read.

//
//  main.m
//  Created by pkxing on 14/12/8.
//  Copyright (c) 2014年 梦醒. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "CZPerson.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        // 1.创建一个 person 对象
        CZPerson *person = [[CZPerson alloc] init];
        person.name = @"pkxing";
        person.age = 27;
        
        // 2.将 person 对象保存到指定的文件中
        NSString *filePath = @"/Users/pkxing/desktop/person.data";
        [NSKeyedArchiver archiveRootObject:person toFile:filePath];
        
        // 3.从文件中读取 person 对象
        CZPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        NSLog(@"%@",p);
    }
}
Summary: Use NSKeyedArchiver save an object to a file in two conditions:

1, you want to save the object must follow NSCoding agreement

2, the protocol must be implemented in the two methods. For more details, please see the code

Published 10 original articles · won praise 1 · views 5892

Guess you like

Origin blog.csdn.net/pkxwyf/article/details/41810167