iOS - 对象的归档与解档(运行时实现)

归档与解档是IOS中一种序列化与反序列化的方式。对象要实现序列化需要遵循NSCoding协议,而绝大多数Foundation和Cocoa Touch类都遵循了NSCoding协议。下面看看具体的实现方式:

1,要归档的类的.h文件


#import 

@interface Person : NSObject
@property (nonatomic, strong)NSString       *name;
@property (nonatomic, assign)NSInteger      age;
+(instancetype)initWithName:(NSString *)name andAge:(NSInteger )age;
- (void)encodeWithCoder:(NSCoder *)coder;
- (instancetype)initWithCoder:(NSCoder *)coder;
@end

2,要归档的类的.m文件

#import "Person.h"
#import 
@implementation Person
+(instancetype)initWithName:(NSString *)name andAge:(NSInteger )age{
    
    Person *per = [[Person alloc]init];
    per.name = name;
    per.age = age;
    return per;
    
}
- (void)encodeWithCoder:(NSCoder *)coder
{
    //告诉系统归档的属性是哪些
    unsigned int count = 0;//表示对象的属性个数
    Ivar *ivars = class_copyIvarList([Person class], &count);
    for (int i = 0; i

3,控制器调用(运行时方式,归档/解档数组对象为例)

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property (strong,nonatomic) NSMutableArray * array;
@end

@implementation ViewController


-(NSMutableArray *)array{
    if (!_array) {
        Person *person1 = [Person initWithName:@"张三" andAge:1];
        Person *person2 = [Person initWithName:@"张三" andAge:2];
        Person *person3 = [Person initWithName:@"张三" andAge:3];
        Person *person4 = [Person initWithName:@"张三" andAge:4];
        _array = [NSMutableArray arrayWithObjects:person1,person2,person3,person4,nil];
    }
    return _array;
}


- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)save:(UIButton *)sender {
    
    ///这里以Documents路径为例,存到temp路径下
    NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [Path stringByAppendingPathComponent:@"historySearch.data"]; //注:保存文件的扩展名可以任意取,不影响。
    NSLog(@"%@", filePath);
    //归档
    [NSKeyedArchiver archiveRootObject:self.array toFile:filePath];
}

- (IBAction)read:(UIButton *)sender {
    //取出归档的文件再解档
  NSString *Path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [Path stringByAppendingPathComponent:@"historySearch.data"];
    //解档
    NSMutableArray *personArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    for (Person *per in personArr) {
        NSLog(@"name = %@, age = %ld",per.name,per.age);
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

你可能感兴趣的:(iOS - 对象的归档与解档(运行时实现))