簡體   English   中英

新對象數據不會在領域中更新

[英]new object data is not updated in realm

使用Alamofire解析Json數據,並將其存儲到領域中並顯示到表中工作正常。 將多個對象添加到領域應用程序時崩潰

傑森:

{ 
"worldpopulation": 
    [
         {
         "rank":1,"country":"China",
         "population":"1,354,040,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/china.png"
         }, 

         {
         "rank":2,"country":"India",
         "population":"1,210,193,422",
         "flag":"http://www.androidbegin.com/tutorial/flag/india.png"
         }, 

         {
         "rank":3,"country":"United States",
         "population":"315,761,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/unitedstates.png"
         }, 

         {
         "rank":4,"country":"Indonesia",
         "population":"237,641,326",
         "flag":"http://www.androidbegin.com/tutorial/flag/indonesia.png"
         }, 
         ] 
} 

第一次僅在表格視圖模型類中顯示國家名稱

class Item : Object
{
    @objc dynamic var name = ""

}

接下來,當將類添加到下一個對象后,我可以將填充添加到表視圖中

class Item : Object
{
    @objc dynamic var name = ""
    @objc dynamic var population = ""

}

這是代碼更新並顯示數據

var realm: Realm!
     var objectsArray: Results<Item> {
        get {
            return realm.objects(Item.self)
        }
    }

解析數據

func jsonparsing()
    {
        let url = URL(string:"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt")

        realm = try! Realm()

        Alamofire.request(url!, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseJSON(completionHandler: {
                response in
                let res = response.result.value as! [String:Any]
                let arrayvalue = res["worldpopulation"] as! [[String:AnyObject]]
                for imagearray in arrayvalue
                {
                    let item = Item()
                    try! self.realm.write {
                        item.name = imagearray["country"] as! String
                       item.population =  imagearray["population"] as! String
                        self.realm.add(item)
                        }
                    self.reloaddata()
                }
             }).resume()

    }

如何將多個對象更新到領域,顯示到表視圖中

將現有對象添加或更新到領域中。 僅當對象具有主鍵時才傳遞true以進行更新。 如果領域中不存在具有相同主鍵值的對象,則將插入該對象。 否則,將使用任何更改的值來更新現有對象。

你應該使用

self.realm.add(item,update:true)

並且應該將主鍵添加到對象

您必須在課程中提供主鍵。

來自領域文檔的信息https://realm.io/docs/swift/latest/#objects-with-primary-keys

如果模型類包含主鍵,則可以使Realm使用Realm()。add(_:update :)根據主鍵值智能地更新或添加對象。

// Creating a book with the same primary key as a previously saved book
let cheeseBook = Book()
cheeseBook.title = "Cheese recipes"
cheeseBook.price = 9000
cheeseBook.id = 1

// Updating book with id = 1
try! realm.write {
    realm.add(cheeseBook, update: true)
}

如果數據庫中已經存在主鍵值為“ 1”的Book對象,則只需更新該對象即可。 如果它不存在,那么將創建一個全新的Book對象並將其添加到數據庫中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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