[英]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.