gpt4 book ai didi

objective-c - 自定义类集合的 NSSecureCoding 问题

转载 作者:太空狗 更新时间:2023-10-30 03:42:11 26 4
gpt4 key购买 nike

我在采用 NSSecureCoding 时遇到了问题。我对一个包含自定义类对象的数组进行编码,该类正确地采用了 NSSecureCoding。当我解码它时,传递类 NSArray(这是我编码的对象的类),它会抛出异常。但是,当用字符串数组做完全相同的事情时,它工作正常。我看不出我的类和 NSString 之间有什么区别。

#import <Foundation/Foundation.h>

@interface Foo : NSObject <NSSecureCoding>
@end
@implementation Foo
- (id)initWithCoder:(NSCoder *)aDecoder {
return [super init];
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
}
+ (BOOL)supportsSecureCoding {
return YES;
}
@end

int main() {
@autoreleasepool {

NSMutableData* data = [[NSMutableData alloc] init];
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:@[[Foo new]] forKey:@"foo"];
[archiver encodeObject:@[@"bar"] forKey:@"bar"];
[archiver finishEncoding];

NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
unarchiver.requiresSecureCoding = YES;
// throws exception: 'value for key 'NS.objects' was of unexpected class 'Foo'. Allowed classes are '{( NSArray )}'.'
[unarchiver decodeObjectOfClass:[NSArray class] forKey:@"foo"];
// but this line works fine:
[unarchiver decodeObjectOfClass:[NSArray class] forKey:@"bar"];
[unarchiver finishDecoding];

}
return 0;
}

最佳答案

您可能已经解决了这个问题,但我刚刚点击并找到了解决方案,我想我会把它留在这里给找到这个的其他人。

我的解决方案是使用 decodeObjectOfClasses:forKey:

迅速:

    if let data = defaults.objectForKey(FinderSyncKey) as? NSData
let unArchiver = NSKeyedUnarchiver(forReadingWithData: data)
unArchiver.setRequiresSecureCoding(true)
//This line is most likely not needed, I was decoding the same object across modules
unArchiver.setClass(CustomClass.classForCoder(), forClassName: "parentModule.CustomClass")
let allowedClasses = NSSet(objects: NSArray.classForCoder(),CustomClass.classForCoder())
if let unarchived = unArchiver.decodeObjectOfClasses(allowedClasses, forKey:NSKeyedArchiveRootObjectKey) as? [CustomClass]{
return unarchived

}
}

在 objective-C 中它会像 [unArchiver decodeObjectOfClasses:allowedClasses forKey:NSKeyedArchiveRootObjectKey]

将解码对象更改为解码对象为我解决了上述异常。

关于objective-c - 自定义类集合的 NSSecureCoding 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24376746/

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