2017-07-09 54 views
0

我正在將數據加載到UITableViewController中,數據來自Realm。所以我在ViewController上有一個屬性:var nextWeekPlants: Results<Plant>!行刪除不更新表視圖

變量像這樣加載:nextWeekPlants = realm.objects(Plant.self).filter("...")在我寫的updateUI()方法中。 updateUI()方法也調用tableView.reloadData()

在我numberOfRowsInSection委託方法,我有這樣的檢查:

if let plants = nextWeekPlants { 
    return plants.count 
} else { 
    return 0 
} 

好吧,它工作正常收集數據,顯示在屏幕上,但只要我從表視圖中刪除1個工廠和想要刪除另一個:它崩潰。 'RLMException', reason: 'Index 1 is out of bounds (must be less than 1)'

我以這種方式刪除設備:

tableView.beginUpdates() 
do { 
    self.realm.beginWrite() 
    self.realm.delete(self.nextWeekPlants[indexPath.row]) 
    try self.realm.commitWrite() 
} catch (let error) { 
    print(error.localizedDescription) 
} 
tableView.deleteRows(at: [indexPath], with: .left) 
tableView.endUpdates() 

它刪除一個廠就好了,但它不會刪除其他。我是否需要以其他方式更新tableView(請撥updateUI()也許?),還是需要更新我的Realm集合?

**編輯**

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    // Little hack to show no extra cells and to make sure the swiping works. 
    self.tableView.allowsMultipleSelectionDuringEditing = false 
    self.tableView.tableFooterView = UIView() 

    updateUI() 
} 

func updateUI() { 
    let calendar = Calendar.current 
    let maxDate = calendar.date(byAdding: .day, value: 7, to: Date()) 

    if let nextWeek = maxDate { 
     nextWeekPlants = realm.objects(Plant.self).filter("nextWater <= %@", nextWeek) 
    } 

    self.tableView.setEditing(false, animated: true) 
    self.tableView.reloadData() 
} 
+0

嘗試reloadData()你最終更新之前,還從nextWeekPlants – RJiryes

+0

@ jbehrens94我猜你需要更新表數組值,以及刪除對象。植物陣列。 –

+0

@RJiryes這將更新tableView兩次,這不是偉大的UI,我想。 @TusharSharma因此,也許我需要再次調用'updateUI()',因爲該方法設置領域集合屬性? – jbehrens94

回答

0

你看上去變異UITableView的狀態,而不讓境界瞭解它。請參閱Realm文檔的Interface-Driven Writes部分。

do { 
    self.realm.beginWrite() 
    self.realm.delete(self.nextWeekPlants[indexPath.row]) 
    tableView.deleteRows(at: [indexPath], with: .left) 
    try self.realm.commitWrite(withoutNotifying: [token]) 
} catch (let error) { 
    print(error.localizedDescription) 
} 
相關問題