iOS 数据归档----温故而知新

#import "StudyViewController.h"

#import "person.h"

@interface StudyViewController ()

@property (nonatomic, copy)NSString *filePath;

@end

 

@implementation StudyViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    person *p1 = [[person alloc]init];

    p1.name = @"zhangshan";

    

    person *p2 = [[person alloc]init];

    p2.name = @"lisi";

    

    person *p3 = [[person alloc]init];

    p3.name = @"wangwu";

    

    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *filePath = [pathArr[0] stringByAppendingPathComponent:@"model"];

    self.filePath = filePath;

    

    //归档单个数据

    //[NSKeyedArchiver archiveRootObject:p toFile:filePath];

    

    //归档多个数据

    NSMutableData *data = [[NSMutableData alloc]init];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

    [archiver encodeObject:p1 forKey:@"p1"];

    [archiver encodeObject:p2 forKey:@"p2"];

    [archiver encodeObject:p3 forKey:@"p3"];

    [archiver finishEncoding];

    if ([data writeToFile:self.filePath atomically:YES]) {

        NSLog(@"归档成功。。。");

    }

    

}

 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    if ([[NSFileManager defaultManager]fileExistsAtPath:self.filePath]) {

        //解档单个数据

//        person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];

//        NSLog(@"p.name =%@",p.name);

        

        //解档多个数据

        NSData *data = [NSData dataWithContentsOfFile:self.filePath];

        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];

        person *p1 = [unarchiver decodeObjectForKey:@"p1"];

        person *p2 = [unarchiver decodeObjectForKey:@"p2"];

        person *p3 = [unarchiver decodeObjectForKey:@"p3"];

 

        NSLog(@"p1 =%@\np2 =%@\np3 =%@",p1.name,p2.name,p3.name);

    }

}

@end

 

#import <Foundation/Foundation.h>

 

@interface person : NSObject<NSCoding>

@property (nonatomic, copy)NSString *name;

@end

 

#import "person.h"

@implementation person

 

-(instancetype)initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self) {

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

    }

    return self;

}

 

-(void)encodeWithCoder:(NSCoder *)aCoder

{

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

}

@end

posted on 2018-10-30 17:41  Truce_Lee  阅读(100)  评论(0编辑  收藏  举报