簡體   English   中英

如何在CoreData中保存Dictionary數組?

[英]How can I save array of Dictionary in CoreData?

如何將數據存儲在CoreData中? 我正在使用它在tableView單元格中顯示它,但是如何保存和從數據庫中檢索呢?

這是代碼:

var arrOfDict = [[String :AnyObject]]()
var dictToSaveNotest = [String :AnyObject]()

class SecondViewController: UIViewController {

   @IBAction func addItem(_ sender: Any)
{
        dictToSaveNotest.updateValue(notesField.text! as AnyObject, forKey: "notesField")
        arrOfDict.append(dictToSaveNotest)
}

然后在tableViewCell中查看,我使用了代碼:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellID") as! CustomCell
cell.textView.text = arrOfDict[indexPath.row]["notesField"] as! String!

}

我在我的addItem嘗試過

 let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let task = Task(context: context)
        task.notes=notesField.text!

        //save the data to coreData
        (UIApplication.shared.delegate as! AppDelegate).saveContext()

但不確定。

是的,通常這就是您保存到Core Data的方式。 您創建該對象的實例。 設置屬性,然后保存。 您收到任何錯誤嗎? 還是只想確保您的代碼有效?

如果要驗證代碼是否有效,最好的辦法是嘗試訪問保存的數據。 如果您可以看到從數據庫中檢索到的已保存數據,那么您的代碼就可以了:)

為了將輸入保存為Task對象,如果您在屏幕上有一個textFieldnotesField可以接受輸入,則可以執行以下操作:

let task = Task(context: context)
task.title = textField.text
task.notes = notesField.text
//save the data to coreData
(UIApplication.shared.delegate as! AppDelegate).saveContext()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM