我剛剛開始,我用UserDefaults一次或兩次,從未使用CoreData,所以我不知道在這種情況下使用。我有一個表格視圖,它具有從一個空數組填充的單元格,該數組由一組字符串填充,具體取決於頁面標題。CoreData VS UserDefaults用於保存用戶刪除
換句話說,我在viewDidLoad中的函數,它檢查navigationItem.title,並根據它是什麼,填充用正確的字符串的空數組。一切都加載好,但我需要刪除的項目,以保持刪除。這裏是我的代碼:
初始化:
static var places = [String]()
var nycPlaces = ["Central Park", "Rockefeller Center", "Empire State Building"]
var londonPlaces = ["London Eye", "Windsor Castle", "Tower of London"]
var parisPlaces = ["Champs Elysee", "Eiffel Tower", "Catacombs"]
這是填充與正確的數組表視圖的功能 - 這就是所謂的在viewDidLoad中:
func populateCells() {
switch navigationItem.title {
case "New York":
ListController.places = nycPlaces
case "London":
ListController.places = londonPlaces
default:
ListController.places = parisPlaces
}
tableView.reloadData()
}
,並刪除,我有:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete
{
tableView.beginUpdates()
ListController.places.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
tableView.endUpdates()
}
}
問題是,當我離開頁面,然後重新導航 - 加載它,空數組重新與3個字符串關聯,而不管之前已刪除哪些。我如何確保刪除的單元格不會回來?
感謝您的幫助!
我要去對照以下問題的答案,說:「學習和使用枚舉核心數據「。試圖使用戶默認操作作爲對象持久性系統,最終會浪費時間,因爲您的應用程序或您的需求變得更加複雜。 – Paulw11
這是一個公平的評論@ Paulw11。這確實取決於你打算如何複雜。如果您希望這些列表在某個地方被RESTful服務的響應填充,或者您希望可能擁有更多類型的位置或子區域,那麼CoreData可能是更可行的選擇。此外,CoreData是一個很好的事情知道無論:) – Jake