Problems with NSSecureCoding with Custom Class Collections

I'm having trouble accepting NSSecureCoding. I am encoding an array containing the objects of my custom class, which correctly accepts NSSecureCoding. When I decode it by passing a class NSArray(which is the class of the encoded object), it throws an exception. However, when you do the same with an array of strings, it works fine. I do not understand 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;
}
+4
source share
1 answer

You probably already decided it, but I just hit it and found a solution, and thought that I would leave it here for everyone who finds it.

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]

.

+6

Source: https://habr.com/ru/post/1545777/


All Articles