LGPerson.h

//
//  LGPerson.h
//  lglx - 01- 数据存储
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 mac. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LGPerson : NSObject
@property (nonatomic , copy) NSString *name;
@property (nonatomic , assign) NSInteger age;
@property (nonatomic , assign) BOOL gender;


@end

LGPerson.m

//
//  LGPerson.m
//  lglx - 01- 数据存储
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LGPerson.h"
@interface LGPerson()<NSCoding>

@end


@implementation LGPerson

/**
 * 解档
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    if (self = [super init]) {
        
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];
        _gender = [aDecoder decodeBoolForKey:@"gender"];
                   }
    
    return self;
}

/**
 * 归档
 */
-(void)encodeWithCoder:(NSCoder *)aCoder {
    
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
    [aCoder encodeBool:_gender forKey:@"gender"];
}

@end

ViewController.m

//
//  ViewController.m
//  lglx - 01- 数据存储
//
//  Created by mac on 16/1/4.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ViewController.h"
#import "LGPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

/**
 * 写入数据
 */
- (IBAction)didClickWtiteDataButton {

    // 创建对象
    LGPerson *person = [[LGPerson alloc] init];
    person.name = @"nuohe";
    person.age = 19;
    person.gender = YES;
    
    // 获取沙盒路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"person.data"];
    NSLog(@"filePath路径\n %@",filePath);
    
    // 进行归档
    [NSKeyedArchiver archiveRootObject:person toFile:filePath];
    

}

/**
 * 读取数据
 */
- (IBAction)didClickReadDataButton {
    
    
    // 获取沙盒路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"person.data"];
    
    LGPerson *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    NSLog(@"%@ - %zd - %d",person.name,person.age,person.gender);
    
}



@end

注意事项:

  归档和解档的类型必须一一对应

  key最好定义为宏 防止写错

  要归档的对象必须遵守NSCoding的协议

posted on 2016-01-04 16:09  诺丶呵  阅读(99)  评论(0)    收藏  举报