![](/img/trans.png)
[英]Store a Dictionary<String, CustomObject> in NSUserDefaults in Swift
[英]Iterate through dictionary of string, customObject and call customObject initialiser
我有一個文件夾,其中包含許多 json 文件。 例如:
a.json
b.json
c.json
c.json2
c.json3
每個文件都包含我需要插入到領域數據庫中的數據。 a = 一種類型的對象,b = 另一種類型的對象,c.json1、c.json2 和 c.json3 都是相同類型的對象,但由於內容的數量,它們被分成了 3 個文件。
我沒有為每種類型的對象分別創建一個 for 循環,而是嘗試創建一個字典,我可以在第二個 for 循環中迭代它。
var filesToProcess : [String: Object] =
["a.json" : A(), "b.json" : B(), "c.json" : C()]
for (str, obj) in filesToProcess {
let numFiles = FileCounter().getNumFilesStartingWith(filename : str, url : unzippedDestinationUrl)
for i in 0...numFiles {
var append : String = ""
i == 0 ? (append = "") : (append = String(i))
if let jsonData = try? Data(contentsOf: unzippedDestinationUrl.appendingPathComponent(str+append)){
if let array = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [[String: Any]] {
for item in array{
let itemJsonStr = item["data"] as! String
let item = obj(jsonStr : itemJsonStr)
DispatchQueue(label: "background").async {
let realm = try! Realm()
try! realm.write {
realm.add(item)
}
}
}
}
}
}
}
其中 A、B 和 C 是這樣的對象:
import Foundation
import RealmSwift
import Realm
open class A : Object {
open dynamic var _id : String = ""
open dynamic var prop1 : Int = 0
open dynamic var prop2 : String = ""
open override class func primaryKey() -> String? {
return "_id"
}
required public init() {
super.init()
}
public init(jsonStr: String)
{
if let dataDict = try? JSONSerializer.toDictionary(jsonStr){
self._id = dataDict ["id"] as! String
self.prop1 = dataDict ["prop1"] as! Int
self.prop2 = dataDict ["prop2"] as! String
}
super.init()
}
required public init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
required public init(value: Any, schema: RLMSchema) {
fatalError("init(value:schema:) has not been implemented")
}
}
但是在我的 for 循環中:
let item = obj(jsonStr : itemJsonStr)
我收到錯誤:
Cannot call value of Non-function type 'Object'
有沒有辦法解決? 我嘗試做的事情是可能的,還是應該堅持我已經做的事情,即為每種類型的對象創建帶有重復代碼的單獨循環? 注意 A、B 和 C 具有不同的屬性,但都使用 json 類型的輸入字符串進行初始化
obj
是一個對象的實例,你不能這樣稱呼它。
實現您想要的一種方法是創建您的對象的通用超類(例如MyObject
),在那里聲明init(jsonStr: String)
並使您的字典像這樣:
var filesToProcess : [String: MyObject] = ["a.json" : A.self, "b.json" : B.self, "c.json" : C.self]
然后你就可以打電話了
obj.init(jsonStr: ...)
創建一個對象。
您可以使用協議實現相同的目的。
另一種方法是使用閉包來實現:
var filesToProcess: [(String, (String) -> Object)] = [
("a.json", {json in A(jsonStr: json)}),
("b.json", {json in B(jsonStr: json)}),
("c.json", {json in C(jsonStr: json)})
]
然后obj(jsonStr : itemJsonStr)
實際上會起作用。
(注意我使用了一個 2 元組數組而不是字典)。
您可以創建一個新功能
func parse(jsonStr: String) {
if let dataDict = try? JSONSerializer.toDictionary(jsonStr){
self._id = dataDict ["id"] as! String
self.prop1 = dataDict ["prop1"] as! Int
self.prop2 = dataDict ["prop2"] as! String
}
}
而不是這條線
//let item = obj(jsonStr : itemJsonStr)
你可以這樣做
obj.parse(jsonStr: str)
let item = obj
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.