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

2

14

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?

Glyceric answered 30/10, 2014 at 16:23 Comment(0)
E
25

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"];
Eraeradiate answered 28/4, 2015 at 17:12 Comment(0)
S
0

For decoding use below method and check:-

 - (id)decodeObjectForKey:(NSString *)key
Suppletory answered 30/10, 2014 at 17:31 Comment(1)
Why can't we use NSSecureCoding but have to NSCoding?Glyceric

© 2022 - 2024 — McMap. All rights reserved.