要使用NSKeyedArchiver实现自定义对象的序列化,首先需要确保你的自定义对象遵循NSCoding协议。NSCoding协议包括两个必须实现的方法:encodeWithCoder:和initWithCoder:。
@interface CustomObject : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation CustomObject
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInteger:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super init];
if (self) {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
CustomObject *customObject = [[CustomObject alloc] init];
customObject.name = @"John";
customObject.age = 30;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:customObject];
CustomObject *unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
现在你已经成功地使用NSKeyedArchiver实现了自定义对象的序列化和反序列化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。