2016-12-17 34 views
0

enter image description here爲什麼realm數據庫屬性值不更改?

如上圖所示,索引增加一個序列。當我刪除一個索引(0除外),比如3時,我希望所有的索引仍然會按順序通過0〜5,這意味着保持不變,4減少到3,5 - > 4,6-> 5。下面是我的代碼:

let defaultRealm = try! Realm() 
let currentRealm = self.defaultRealm.objects(CurrentRealmObject.self) 

let remainedItems = currentRealm.filter("index > \(indexPath.row)") 

for item in remainedItems { 
    var realmIndex = item.index 
    print("before \(realmIndex)") 

    try! self.defaultRealm.write { 
     realmIndex -= 1 
     print("update \(realmIndex)") 
    } 
} 

之後我刪除索引3,境界數據庫成爲繼: enter image description here

和打印控制檯:

before 6 
update 5 
before 4 
update 3 
before 5 
update 4 

看到了什麼?值實際上是更新的,但是領域數據庫仍然保持索引不變,並且它的序列變得混亂(我也想知道爲什麼 - !以及如何保持它們在相同的序列中)。

感謝您的幫助!

回答

1

var realmIndex = item.index意味着item.index被複制到realmIndex。無論您更改了多少複製值,都不會影響原始對象。要更新Realm的值,請重新指定它或直接操作屬性而不是複製的值。

  1. 指定再次

    try! self.defaultRealm.write { 
        realmIndex -= 1 
        item.index = realmIndex 
    } 
    
  2. 直接操縱性能

    try! self.defaultRealm.write { 
        item.index -= 1 
    } 
    

對於序列,作爲同其他數據庫,境界不守秩序。如果您想按順序獲得結果,則需要使用sorted()方法進行明確排序。或者,使用Realm的List<T>代替。 List<T>保持訂單。

+0

謝謝!第一個問題解決了。你知道如何修復對象的序列嗎?像上面一樣,0,1,2,3,4,5,6,當我刪除索引3時,我希望序列爲0,1,2,4,5,6,但不是0,1,2,6 ,4,5,我需要將該索引作爲pageController的頁面引用,奇怪的序列更改會使頁面混淆。 – stephen

+0

@steve 對於序列,與其他數據庫相同,Realm不保留順序。如果您想要按順序獲得結果,則需要使用'sorted()'方法進行顯式排序。或者,使用Realm的'List '代替。 '清單'保持訂單。我也編輯了我的答案。 –