存储用法之NSKeyedArchiver

Person.h

#import <Foundation/Foundation.h>

@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<NSCoding>
#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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容