[英]Secure coding of Set<CustomObject>
我的应用程序使用核心数据,它存储自定义 class CustomClass
的实例。
这个 class 有许多属性,其中大部分是标准类型,但一个属性是xxx: Set<CustomObject>
。
因此, xcdatamodeld
指定(在其他标准类型中)一个Transformable
类型的属性xxx
。 xxx
是Set<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>
我现在必须使用decodeObject(of:forKey:)
,其中of
是要解码的 object 的类型,这里输入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>>')
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>
?
不幸的是,我在 Apple 文档中找不到任何内容,但我在这篇文章中找到了解决方案的提示:
NSSecureCoding
不适用于所有标准 swift 类。 对于那些不支持它的类,必须使用 Objective-C 对应类,即NSString
而不是String
。
一个例子:如果必须对var string = "String"
进行安全编码,则必须使用例如aCoder.encode(string as NSString, forKey: „string“)
。
现在NSSecureCoding
目前不支持Set
。 我不得不这样使用
let aSet: Set<CustomObject> = []
aCoder.encode(aSet as NSSet, forKey: „aSet“)
和
let decodedSet = aDecoder.decodeObject(of: NSSet.self, forKey: „aSet“) as? Set<CustomObject>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.