Unexpected class error when encoding / decoding NSArray with NSSecureCoding
Background
We have several classes that follow the protocol NSSecureCoding
.
@interface ClassA : NSObject <NSSecureCoding>
// ...
@end
@interface ClassB : NSObject <NSSecureCoding>
// ...
@end
Note that it NSArray
also matches NSSecureCoding
. Therefore, we try to do the following.
For encoding:
NSArray* array = ...
[archiver encodeObject:array forKey:@"AirdropDataKey"];
For decoding
NSArray* array = [unarchiver decodeObjectOfClass:[NSArray class]
forKey:@"AirdropDataKey"];
And I am getting the following error.
Application terminated due to uncaught exception "NSInvalidUnarchiveOperationException", reason: "The value for key" NS.objects "was unexpected class" ClassA ". Valid classes: {{NSArray
)} ''
Can anyone please explain why and can this problem be solved?
Edit
I think I figured it out. Please refer to my underwriter in the following message. Good luck ~
source to share
NSCoder
provides an additional method decodeObjectOfClasses:forKey:
where a set of expected objects can be passed. This allows you to decode nested structures.
Just pass the set with NSArray
both yours ClassA
and ClassB
class:
NSSet *classes = [NSSet setWithObjects:[NSArray class], [ClassA class] ,[ClassB class], nil];
NSArray* array = [unarchiver decodeObjectOfClasses:classes forKey:@"AirdropDataKey"];
source to share