NSSecureCoding trouble with collections of custom class

懵懂的女人 提交于 2019-12-30 03:20:07

问题


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;
}

回答1:


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.

My solution was to use decodeObjectOfClasses:forKey:

In swift:

    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

        }    
    }

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.



来源:https://stackoverflow.com/questions/24376746/nssecurecoding-trouble-with-collections-of-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!