gpt4 book ai didi

objective-c - "The data couldn’ 无法写入,因为它的格式不正确“在使用 NSKeyedArchiver 归档自定义类时发生

转载 作者:行者123 更新时间:2023-12-04 02:59:02 24 4
gpt4 key购买 nike

我在 iOS12 中尝试了一个新的 API:

[NSKeyedArchiver archivedDataWithRootObject:<#(nonnull id)#> requiringSecureCoding:<#(BOOL)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>]

我想做的很简单,归档一个自定义类,代码如下:

一个名为 Cat 的类:

@interface Cat : NSObject <NSCoding>

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;

+ (void)saveThisCat:(Cat *)cat;
+ (Cat *)getThisCat;

@end


@implementation Cat

- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}

+ (void)saveThisCat:(Cat *)cat {
NSError *error = nil;
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [docPath stringByAppendingPathComponent:@"cat.plist"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cat requiringSecureCoding:YES error:&error];
// ***Error occurs here!!!***
NSLog(@"=== Error Info: %@ ===", [error localizedDescription]);
[data writeToFile:filePath atomically:YES];
}

+ (Cat *)getThisCat {
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [docPath stringByAppendingPathComponent:@"cat.plist"];
Cat *retVal = [NSKeyedUnarchiver unarchivedObjectOfClass:[Cat class] fromData:[NSData dataWithContentsOfFile:filePath] error:nil];
return retVal;
}

@end

用法:

Cat *totoro = [Cat new];
totoro.name = @"totoro";
totoro.age = 1;

NSLog(@"=== The cat's name is %@", totoro.name);
NSLog(@"=== The cat's age is %d", totoro.age);

[Cat saveThisCat:totoro];

Cat *resultCat = [Cat getThisCat];

NSLog(@"=== The cat's name is %@", resultCat.name);
NSLog(@"=== The cat's age is %d", resultCat.age);

以及错误信息(在执行 saveThisCat 方法时使用 archivedDataWithRootObject 生成)

=== Error Info: The data couldn’t be written because it isn’t in the correct format. ===

有什么问题吗?请指出,非常感谢!

最佳答案

你必须采用 NSSecureCoding

@interface Cat : NSObject <NSSecureCoding>

并在实现中添加所需的类属性

+ (BOOL)supportsSecureCoding {
return YES;
}

关于objective-c - "The data couldn’ 无法写入,因为它的格式不正确“在使用 NSKeyedArchiver 归档自定义类时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55990322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com