-
Notifications
You must be signed in to change notification settings - Fork 0
NSCoding协议 与NSCoder类、NSKeyedArchiver类
miaohy edited this page Dec 8, 2020
·
2 revisions
1、NSCoding协议使用.
//遵循NSCoding协议
@interface HYCoding : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *hobby;
@end
//encode 属性
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeObject:self.hobby forKey:@"hobby"];
}
//decode属性
-(instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.name = [coder decodeObjectForKey:@"name"];
self.hobby = [coder decodeObjectForKey:@"hobby"];
}
return self;
}
//测试
+(void)testCoding{
HYCoding *coding = [[HYCoding alloc] init];
coding.name = @"sds";
coding.hobby = @"sdds";
HYCoding *coding1 = [[HYCoding alloc] init];
coding1.name = @"sds";
coding1.hobby = @"sdds";
NSArray *array = [NSArray arrayWithObjects:coding,coding1, nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
NSArray *array_unarchiver = [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
2、 NSCoder类、NSKeyedArchiver类 内部如何实现的呢?