归档操作关键步骤
- 确保自定义对象遵循
NSCoding
协议,并实现 encodeWithCoder:
方法。在该方法中,将对象的属性编码到 NSCoder
中。
- 创建一个
NSMutableData
对象用于存储归档后的数据。
- 创建一个
NSKeyedArchiver
对象,并使用 initForWritingWithMutableData:
方法初始化,传入 NSMutableData
对象。
- 使用
encodeObject:forKey:
方法将自定义对象编码到 NSKeyedArchiver
中。
- 调用
finishEncoding
方法完成编码。
- 将
NSMutableData
对象写入文件或进行其他持久化操作。
归档代码示例
#import <Foundation/Foundation.h>
@interface CustomObject : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation CustomObject
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
NSString *name = [aDecoder decodeObjectForKey:@"name"];
NSInteger age = [aDecoder decodeIntegerForKey:@"age"];
self = [super init];
if (self) {
self.name = name;
self.age = age;
}
return self;
}
@end
// 归档操作
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
CustomObject *customObject = [[CustomObject alloc] init];
customObject.name = @"John";
customObject.age = 30;
[archiver encodeObject:customObject forKey:@"customObject"];
[archiver finishEncoding];
// 将data写入文件
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"customObject.archive"];
[data writeToFile:filePath atomically:YES];
解档操作关键步骤
- 从文件或其他持久化存储中读取归档数据,创建一个
NSData
对象。
- 创建一个
NSKeyedUnarchiver
对象,并使用 initForReadingWithData:
方法初始化,传入 NSData
对象。
- 使用
decodeObjectForKey:
方法从 NSKeyedUnarchiver
中解码出自定义对象。
- 调用
finishDecoding
方法完成解码。
解档代码示例
// 解档操作
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"customObject.archive"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
CustomObject *decodedObject = [unarchiver decodeObjectForKey:@"customObject"];
[unarchiver finishDecoding];
NSLog(@"Name: %@, Age: %ld", decodedObject.name, (long)decodedObject.age);