2017-05-09 10 views
4

Imこのエラーが発生するテーブルビューのレルムからオブジェクトを削除しようとするたびに、オブジェクトはに属しているレルムからしか削除できません。ここに関連するコードは次のとおりです。オブジェクトが属しているレルムからオブジェクトを削除できるのは

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

レルムに格納されている実際のレルムオブジェクトではなく、コレクションに格納されているレルムオブジェクトのコピーを削除しようとしています。 CheklistDataModelの定義なし

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

、私はNSPredicateの権利を得たかどうかわからないですが、あなたはここからそれを把握することができるはずです。

0

共有したコードスニペットから、新しいChecklistDataModelオブジェクトを作成しているように見えますが、それらをレルムに追加することはできません。次に、try! realm.writeブロックのレルムからこれらのオブジェクトを削除しようとします。

単にオブジェクトをインスタンス化しても、それがレルムに追加されたわけではありません。成功した書き込みトランザクションによってRealmに追加されるまで、他のSwiftインスタンスと同様に動作します。オブジェクトをレルムに追加した後でのみ、そのレルムからオブジェクトを正常に削除できます。

関連する問題