2015-10-21 57 views
1

警告:我是iOS,Swift和Realm的新手。使用Realm保存和檢索時沒有問題,但似乎無法在不崩潰的情況下更新現有對象。試圖在swift中更新領域對象時獲取SIGABRT

的AppDelegate:

class Bale: Object { 
    dynamic var uid = NSUUID().UUIDString 
    dynamic var id = 0 
    dynamic var number = 0 
    dynamic var type = 0 
    dynamic var weight = 0 
    dynamic var size = "" 
    dynamic var notes = "" 
    override static func primaryKey() -> String? { 
     return "uid" 
    } 
} 

在別處:(Xcode中堅持所有的!)

let bale: Bale = getBaleByIndex(baleSelected) 
    bale.id = Int(textID.text!)! 
    bale.number = Int(textNumber.text!)! 
    bale.type = Int(textType.text!)! 
    bale.weight = Int(textWeight.text!)! 
    bale.size = textSize.text! 
    bale.notes = textNotes.text! 

    try! realm.write { 
     realm.add(bale, update: true) 
    } 

getBaleByIndex:

func getBaleByIndex(index: Int) -> Bale { 
    return bales[index] 
} 

我從getBaleByIndex返回罷了對象讀取數據在其他地方,這樣的功能正常工作。我在上得到了SIGABRT類AppDelegate:UIResponder,UIApplicationDelegate {。沒有完整的示例顯示領域文檔或示例中的更新。我也嘗試使用realm.create和適當的參數,但仍然是不行。它看起來很簡單,所以我確信我在做一些愚蠢的事情。任何幫助都會很棒。謝謝!

+0

見http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1 – rmaddy

+0

你是如何加入第一次的對象?你在哪裏得到這種捆包陣列?共享更多代碼可能會有所幫助 – Shripada

回答

2

什麼是你在這裏咬的是,一旦你添加一個對象到領域,數據不是隻存儲在內存中,而是直接存儲在持久存儲中。您必須在寫入事務中對您的對象執行所有修改,並且在寫入事務提交後它們將自動生效。如果它之前一直存在,則不需要再次將其添加到Realm中。所以,你需要更改您的代碼是這樣的:

try! realm.write { 
    let bale: Bale = getBaleByIndex(baleSelected) 
    bale.id = Int(textID.text!)! 
    bale.number = Int(textNumber.text!)! 
    bale.type = Int(textType.text!)! 
    bale.weight = Int(textWeight.text!)! 
    bale.size = textSize.text! 
    bale.notes = textNotes.text! 

    // Not needed, but depends on the implementation of `getBaleByIndex` 
    // and whether there is the guarantee that it always returns already 
    // persisted objects. 
    //realm.add(bale, update: true) 
} 
+0

這爲我做了詭計。根據Realm文檔,帶有update:.add的.add應添加它,如果它尚不存在,並且編輯現有(如果它已經存在)(基於對象中的主鍵UUID)。我可能沒有按照他們推薦的方式進行,但是您的解決方案按照我的希望編輯和保存數據。 – user3068774

+0

只有在您正在處理尚未保存的新實例時纔有效。因此,如果你不需要與現有屬性合併,你可以通過'getBaleByIndex'來替代實例化一個新的'Bale()',而不是先檢索現有的屬性。 – marius