Arrays Swift和NSCoding:对符合纯类协议的对象数组进行编码

Arrays Swift和NSCoding:对符合纯类协议的对象数组进行编码,arrays,swift,protocols,nscoding,Arrays,Swift,Protocols,Nscoding,我有一个类,StandardObject,它符合协议Object。另一个类,ObjectManager,有一个名为objects的属性,它是一个数组,包含Object的实例。StandardObject和ObjectManager都是NSObject的子类,并且符合NSCoding 当我尝试在encodeWithCoder:中对ObjectManager的对象属性进行编码时,我收到一个错误: cannot convert value of type '[Object]' to expected

我有一个类,
StandardObject
,它符合协议
Object
。另一个类,
ObjectManager
,有一个名为
objects
的属性,它是一个数组,包含
Object
的实例。
StandardObject
ObjectManager
都是
NSObject
的子类,并且符合
NSCoding

当我尝试在
encodeWithCoder:
中对
ObjectManager
对象
属性进行编码时,我收到一个错误:

cannot convert value of type '[Object]' to expected argument type 'AnyObject?'
这是我的密码:

ObjectManager

class ObjectManager: NSObject, NSCoding {

    var objects = [Object]()

    required init?(coder aDecoder: NSCoder) {

    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(objects, forKey: "Objects") //// ERROR HERE
    }

}
对象
协议:

protocol Object: class, NSCoding {
    // Currently completely empty
}
StandardObject

class StandardObject: NSObject, Object {

    required init?(coder aDecoder: NSCoder) {

    }

    func encodeWithCoder(aCoder: NSCoder) {

    }

}
我知道这与您只能对对象(或它们的数组)进行编码有关,而不能对结构、枚举或本例中的协议进行编码。但是,
对象
协议的声明是:

protocol Object: class, NSCoding
这意味着只有类才能符合此协议

这难道不意味着
对象
数组中只有类的实例吗?为什么它不能被编码

我还尝试在编码之前将数组强制转换为NSArray,但出现以下错误:

cannot convert value of type '[Object]' to type 'NSArray' in coercion
下面是我的两个问题:

  • 如果我让
    对象
    协议只有符合它的对象,那么
    对象
    数组不应该是对象数组吗
  • 如果问题1由于某种原因无法实现,您如何将
    对象
    的数组转换为能够使用
    NSCoding
    进行编码

  • 您需要将协议声明为
    @objc
    ,以将其放入
    Objective-C
    世界:

    @objc protocol Object: class, NSCoding {
    
    编译器将知道他将能够使用
    NSArray
    免费桥接Swift数组,因为您将只能使用从
    NSObject
    派生的类的实例构建数组