#import <Foundation/Foundation.h>
#warning 归档第一步:让model签订NSCoding协议
@interface Student : NSObject<NSCoding>
@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSInteger age;
@property(nonatomic,copy)NSString *gender;
@end
#import "Student.h"
@implementation Student
#warning 归档第二步:对model属性进行编码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.gender forKey:@"gender"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
#warning 归档第三步:对model进行解码
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name =
[aDecoder decodeObjectForKey:@"name"];
self.gender =
[aDecoder decodeObjectForKey:@"gender"];
self.age =
[aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
/***************写入model*************************/
//缓存自定义model模型数据
//需要使用iOS中归档/反归档,专门来存储model数据到本地
#warning 归档第四步:对model进行归档操作
Student *stu = [[Student alloc]init];
stu.name = @"大水杯";
stu.gender = @"男";
stu.age = 18;
NSString *archiverPath = [documentPath stringByAppendingPathComponent:@"student"];
//归档类
BOOL result3 =
[NSKeyedArchiver archiveRootObject:stu toFile:archiverPath];
if (result3) {
NSLog(@"归档成功");
}else
{
NSLog(@"归档失败");
}
//反归档取出model数据
Student *stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
NSLog(@"name = %@ %@ %ld",stu1.name,stu1.gender,stu1.age);
/***************写入model*************************/
model归档
最新推荐文章于 2023-10-16 22:58:11 发布
本文介绍了如何在Objective-C中实现NSCoding协议,对自定义的Student模型进行归档和反归档操作,包括签订NSCoding协议、编码模型属性、解码模型以及实际的归档和反归档步骤。通过这些步骤,可以将模型数据存储到本地并读取。
摘要由CSDN通过智能技术生成