如何在Swift中实现decodeObjectOfClasses

时间:2014-06-09 22:12:50

标签: ios swift

我无法找到符合 Swift NSSecureCoding协议的正确方法,特别是在解码作为其他对象数组的对象时。

我无法在swift中创建NSSet类类型。

在Objective-C中我会使用

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

我遇到了像这样创建NSSet的问题:

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

这是错误:

Type 'NSArray.Type' does not conform to protocol 'AnyObject'

3 个答案:

答案 0 :(得分:1)

对于简单对象:

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

自Swift 3.0以来:

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

对于嵌套对象:

NSSet(objects: [NSArray.self, Book.self])

答案 1 :(得分:0)

<强> Declaration

SWIFT

func decodeObjectOfClasses(_ classes: NSSet,
                    forKey key: String) -> AnyObject?

自Swift 3.0以来:

func decodeObject<DecodedObjectType where DecodedObjectType : NSCoding, DecodedObjectType : NSObject>(of cls: DecodedObjectType.Type, forKey key: String) -> DecodedObjectType?

目的-C

- (id)decodeObjectOfClasses:(NSSet *)classes
                     forKey:(NSString *)key

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

答案 2 :(得分:-1)

与我最初发布问题时的情况不完全相同,但我已经通过使用类型集合实现了我想要的效果,如下所示

class Bookshelf: NSObject, NSSecureCoding {
    var authors = [Author]()
    var books = [Book]()

    override init () {
        super.init()
    }

    @objc func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.authors, forKey: "authors")
        aCoder.encodeObject(self.books, forKey: "books")
    }

    @objc required init?(coder aDecoder: NSCoder) {
        self.authors = (aDecoder.decodeObjectForKey("authors") as? [Author])!
        self.books = (aDecoder.decodeObjectForKey("books") as? [Book])!
    }

    @objc static func supportsSecureCoding() -> Bool {
        return true
    }
}