您好,登錄后才能下訂單哦!
要使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。