问题描述
我在采用NSSecureCoding时遇到了麻烦.我对包含自定义类的对象的数组进行编码,该类正确采用了NSSecureCoding
.当我解码它时,传递类NSArray
(这是我编码的对象的类),它将引发异常.但是,当完全相同的事情与字符串数组一起使用时,它可以很好地工作.我看不到我的类和NSString有什么区别.
I am having trouble with adopting NSSecureCoding. I encode an array containing objects of my custom class, which adopts NSSecureCoding
properly. When I decode it, passing the class NSArray
(which is the class of the object I encoded), it throws an exception. However, when do the exact same thing with an array of strings, it works fine. I fail to see what is the difference between my class and 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;
}
推荐答案
您可能已经解决了这个问题,但是我刚刚找到了解决方案,并认为我会将它留给所有找到此解决方案的人使用.
You've probably already solved this, but I just hit this and found a solution, and thought I'd leave it here for anyone else that finds this.
我的解决方案是使用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]
in objective-C it would be something like [unArchiver decodeObjectOfClasses:allowedClasses forKey:NSKeyedArchiveRootObjectKey]
将解码对象更改为解码对象对我来说解决了上述异常.
The change in decode object to decode objects solved the above exception for me.
这篇关于NSSecureCoding自定义类集合的麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!