簡體   English   中英

Set的安全編碼<customobject></customobject>

[英]Secure coding of Set<CustomObject>

我的應用程序使用核心數據,它存儲自定義 class CustomClass的實例。
這個 class 有許多屬性,其中大部分是標准類型,但一個屬性是xxx: Set<CustomObject>
因此, xcdatamodeld指定(在其他標准類型中)一個Transformable類型的屬性xxx xxxSet<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM