MST

星途 面试题库

面试题:Objective-C中归档与解档技术的基础使用

在Objective-C中,简述如何对一个自定义对象进行归档与解档操作?请写出关键步骤和代码示例。假设自定义对象遵循了<NSCoding>协议。
17.5万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

归档操作关键步骤

  1. 确保自定义对象遵循 NSCoding 协议,并实现 encodeWithCoder: 方法。在该方法中,将对象的属性编码到 NSCoder 中。
  2. 创建一个 NSMutableData 对象用于存储归档后的数据。
  3. 创建一个 NSKeyedArchiver 对象,并使用 initForWritingWithMutableData: 方法初始化,传入 NSMutableData 对象。
  4. 使用 encodeObject:forKey: 方法将自定义对象编码到 NSKeyedArchiver 中。
  5. 调用 finishEncoding 方法完成编码。
  6. 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];

解档操作关键步骤

  1. 从文件或其他持久化存储中读取归档数据,创建一个 NSData 对象。
  2. 创建一个 NSKeyedUnarchiver 对象,并使用 initForReadingWithData: 方法初始化,传入 NSData 对象。
  3. 使用 decodeObjectForKey: 方法从 NSKeyedUnarchiver 中解码出自定义对象。
  4. 调用 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);