在 iOS 中使用安全编码取消归档自定义对象
Unarchive custom object with secure coding in iOS
我正在像这样成功地对符合 NSSecureCoding
的对象数组进行编码。
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
如何取消存档此数据?我正在尝试这样,但它返回 nil。
NSError *error = nil;
NSArray<MyClass *> *array = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:data error:&error];
这是错误吧returns。
The data couldn’t be read because it isn’t in the correct format.
这是一个简单的例子
@interface Secure:NSObject<NSSecureCoding> {
NSString* name;
}
@property NSString* name;
@end
@implementation Secure
@synthesize name;
// Confirms to NSSecureCoding
+ (BOOL)supportsSecureCoding {
return true;
}
- (void)encodeWithCoder:(nonnull NSCoder *)coder {
[coder encodeObject:self.name forKey: @"name"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
self = [self init];
if (self){
self.name = [coder decodeObjectOfClass:[NSString class] forKey:@"name"];
}
return self;
}
@end
用法
Secure *archive = [[Secure alloc] init];
archive.name = @"ARC";
NSArray* array = @[archive];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
NSArray<Secure *> *unarchive = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSObject class] fromData:data error:nil];
NSLog(@"%@", unarchive.firstObject.name);
我正在像这样成功地对符合 NSSecureCoding
的对象数组进行编码。
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
如何取消存档此数据?我正在尝试这样,但它返回 nil。
NSError *error = nil;
NSArray<MyClass *> *array = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:data error:&error];
这是错误吧returns。
The data couldn’t be read because it isn’t in the correct format.
这是一个简单的例子
@interface Secure:NSObject<NSSecureCoding> {
NSString* name;
}
@property NSString* name;
@end
@implementation Secure
@synthesize name;
// Confirms to NSSecureCoding
+ (BOOL)supportsSecureCoding {
return true;
}
- (void)encodeWithCoder:(nonnull NSCoder *)coder {
[coder encodeObject:self.name forKey: @"name"];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
self = [self init];
if (self){
self.name = [coder decodeObjectOfClass:[NSString class] forKey:@"name"];
}
return self;
}
@end
用法
Secure *archive = [[Secure alloc] init];
archive.name = @"ARC";
NSArray* array = @[archive];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array requiringSecureCoding:YES error:nil];
NSArray<Secure *> *unarchive = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSObject class] fromData:data error:nil];
NSLog(@"%@", unarchive.firstObject.name);