2017-05-09 45 views
4

我得到這個錯誤「只能從它屬於的領域刪除一個對象」每次我嘗試從我的tableview領域刪除一個對象。下面是相關代碼:只能從它所屬的領域刪除一個對象

let realm = try! Realm() 
var checklists = [ChecklistDataModel]() 

override func viewWillAppear(_ animated: Bool) { 


    checklists = [] 
    let getChecklists = realm.objects(ChecklistDataModel.self) 

    for item in getChecklists{ 

     let newChecklist = ChecklistDataModel() 
     newChecklist.name = item.name 
     newChecklist.note = item.note 

     checklists.append(newChecklist) 
    } 

    tableView.reloadData() 

} 

override func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return checklists.count 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistCell", for: indexPath) as! ListsTableViewCell 

    cell.name.text = checklists[indexPath.row].name 
    return cell 
} 

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 

     // Delete the row from the data source 
     try! realm.write { 
      realm.delete(checklists[indexPath.row]) 
     } 

     //delete locally 
     checklists.remove(at: indexPath.row) 

     self.tableView.deleteRows(at: [indexPath], with: .fade) 
    } 
} 

我知道這是這部分是具體的:

 // Delete the row from the data source 
     try! realm.write { 
      realm.delete(checklists[indexPath.row]) 
     } 

是怎麼回事的任何想法? 在此先感謝!

回答

8

您正在嘗試刪除存儲在集合中的Realm對象的副本,而不是Realm中存儲的實際Realm對象的副本。

try! realm.write { 
    realm.delete(Realm.objects(ChecklistDataModel.self).filter("name=%@",checklists[indexPath.row].name)) 
} 

沒有CheklistDataModel的定義,我不知道如果我得到了NSPredicate權利,但你應該能夠從這裏找到答案。

0

從您共享的代碼片段看來,您似乎創建了新的ChecklistDataModel對象,但從未將它們添加到任何領域。然後嘗試從try! realm.write區塊的Realm中刪除這些對象。

簡單地實例化一個對象並不意味着它已被添加到領域;直到通過成功的寫入事務將其添加到Realm中,它的行爲就像任何其他Swift實例一樣。只有在將對象添加到領域後,才能成功從同一個領域中刪除它。

相關問題