我正在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 - 使用NSKeyedArchiver归档自定义类时,发生“由于格式不正确而无法写入数据”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55990322/

10-09 16:32