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
下面是我的两个问题:
对象
协议只有符合它的对象,那么对象
数组不应该是对象数组吗对象
的数组转换为能够使用NSCoding
进行编码您需要将协议声明为
@objc
,以将其放入Objective-C
世界:
@objc protocol Object: class, NSCoding {
编译器将知道他将能够使用NSArray
免费桥接Swift数组,因为您将只能使用从NSObject
派生的类的实例构建数组