1

我的应用程序使用存储自定义类实例的核心数据CustomClass
此类具有许多属性,其中大多数是标准类型,但一个属性是xxx: Set<CustomObject>.
因此xcdatamodeld指定(在其他标准类型xxx中) type的属性TransformablexxxSet<CustomObject>。它的类型是Optional,Transformer 现在是NSSecureUnarchiveFromData
之前没有指定 Transformer,因此解码不安全。但 Apple 现在建议使用安全编码,因为将来不推荐使用不安全编码。

为了启用安全编码,我做了以下事情:
CustomClass现在采用NSSecureCoding而不是NSCoding.
以下内容var已添加到CustomClass

public static var supportsSecureCoding: Bool { get { return true } }  

然后我尝试修改public required convenience init?(coder aDecoder: NSCoder) {…},以便xxx安全地解码该属性。我知道,而不是

let xxx = aDecoder.decodeObject(forKey: „xxx“) as? Set<CustomObject>  

我必须使用 now decodeObject(of:forKey:)of要解码的对象的类型在哪里,这里是 type Set<CustomObject>
我的问题是我不知道如何制定这个:如果我使用

let xxx = aDecoder.decodeObject(of: Set<CustomObject>.self, forKey: „xxx“)  

我得到错误Cannot convert value of type 'Set<CustomObject>.Type' to expected argument type '[AnyClass]?' (aka 'Optional<Array<AnyObject.Type>>‘)
显然编译器没有编译

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

但反而

func decodeObject(of classes: [AnyClass]?, forKey key: String) -> Any?

即它Set<CustomObject>不被视为单一类型,而是作为类型的集合。

那么,我如何指定只应解码一种类型,即Set<CustomObject>

4

1 回答 1

1

不幸的是,我在 Apple 文档中找不到任何内容,但我在这篇文章
NSSecureCoding中找到了解决方案的提示:不适用于所有标准 swift 类。对于那些不支持它的类,必须使用 Objective-C 对应类,即,NSString而不是String.

一个例子:如果var string = "String"必须进行安全编码,则必须使用 eg aCoder.encode(string as NSString, forKey: „string“)

现在目前Set不支持NSSecureCoding。我不得不这样使用

let aSet: Set<CustomObject> = []
aCoder.encode(aSet as NSSet, forKey: „aSet“)  

let decodedSet = aDecoder.decodeObject(of: NSSet.self, forKey: „aSet“) as? Set<CustomObject>
于 2019-10-01T07:18:03.103 回答