Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error of Unexpected class while encode/decode an NSArray with NSSecureCoding

Background

We have multiple classes that conform to NSSecureCoding protocol.

@interface ClassA : NSObject <NSSecureCoding>
// ...
@end

@interface ClassB : NSObject <NSSecureCoding>
// ...
@end

We notice that NSArray also conforms to NSSecureCoding. Therefore, we try the following.

For encoding:

NSArray* array = ...
[archiver encodeObject:array forKey:@"AirdropDataKey"];

For decoding

NSArray* array = [unarchiver decodeObjectOfClass:[NSArray class] 
                                          forKey:@"AirdropDataKey"];

And I get this following error message.

Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'value for key 'NS.objects' was of unexpected class 'ClassA'. Allowed classes are '{(
NSArray
)}'.'

Anybody could explain why and whether it is possible to resolve this issue?

like image 448
Yuchen Avatar asked Oct 30 '14 16:10

Yuchen


1 Answers

NSCoder provides an additional method decodeObjectOfClasses:forKey:, where a set of expected objects could be passed. This allows to decode nested structures.

Just pass a set with the NSArray and your ClassA and ClassB class:

NSSet *classes = [NSSet setWithObjects:[NSArray class], [ClassA class] ,[ClassB class], nil];
NSArray* array = [unarchiver decodeObjectOfClasses:classes forKey:@"AirdropDataKey"];
like image 56
simonseyer Avatar answered Oct 12 '22 09:10

simonseyer