存储用法之NSKeyedArchiver

Person.h

#import 

@interface LoginModel : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;

@end

Person.m

#import "LoginModel.h"
#import "MJExtension.h"

@implementation LoginModel
//cording
MJExtensionCodingImplementation

@end

或者
Person.m

#import "Person.h"
//遵守NSCoding协议
@implementation LoginModel
#pragma mark 编码,对象属性进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//前者(_age,_name)是属性,后者是关键字Key(age,name)
    [aCoder encodeInt:_age forKey:age];
    [aCoder encodeObject:_name forKey:name];
}

#pragma mark 解码,解码归档数据初始化对象
- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        _idNum = [aDecoder decodeIntForKey:age];
        _name = [aDecoder decodeObjectForKey:name];
    }
    return self;
}

ViewController1:
保存数据

Person *p=[[Person alloc] init];
p.name=@"小王";
p.age=12;

//设置保存路径
NSString * CLSLoginDataPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingString:@"CLSLOGINDATA.data"];

//Encoding保存LoginModel
[NSKeyedArchiver archiveRootObject:loginModel toFile:CLSLoginDataPath];

ViewController2:
读取数据

NSString * CLSLoginDataPath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingString:@"CLSLOGINDATA.data"]
// Decoding
Person*p = [NSKeyedUnarchiver unarchiveObjectWithFile:CLSLoginDataPath];
NSString*name=p.name;
int age=p.age;

你可能感兴趣的:(存储用法之NSKeyedArchiver)