Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement decodeObjectOfClasses in Swift

Tags:

ios

swift

I'm having trouble finding the correct way to conform the the NSSecureCoding protocol in Swift, specifically when decoding objects that is an array of other objects.

I can't create an NSSet of class types in swift.

In Objective-C I would use

self.books = [aDecoder decodeObjectOfClasses:[NSSet setWithObjects:[NSArray class], [Book class], nil] forKey:@"books"];

in Swift I'm having issues creating the NSSet like this :

self.books = aDecoder.decodeObjectOfClasses(NSSet().setByAddingObject(NSArray.self).setByAddingObject(Book.self), forKey:"books")

Here's the error:

Type 'NSArray.Type' does not conform to protocol 'AnyObject'
like image 936
Tim Sawtell Avatar asked Jun 09 '14 22:06

Tim Sawtell


1 Answers

For simple objects:

self.myObject = aDecoder.decodeObjectOfClass(MyObject.self, forKey: "myObject")!

Since Swift 3.0:

self.myObject = aDecoder.decodeObject(of:MyObject.self, forKey: "myObject")!

For nested objects:

NSSet(objects: [NSArray.self, Book.self])
like image 57
stoffen Avatar answered Sep 19 '22 15:09

stoffen