2017-09-19 43 views
1

我有一個tableview。點擊上面有一個按鈕,彈出一個帶有textField的警報,我可以在textField上輸入一些數據。點擊'確定'後,alertview上的內容將填充到tableview中。我也將這些數據存儲在CoreData中。在桌面視圖上持久化數據(存儲在coredata中)問題

但問題是,當我關閉應用程序或導航到另一個屏幕時,tableview中的數據已被刪除,而它應該保留並保留在屏幕上,即使在導航到另一個屏幕或關閉應用程序時也是如此存儲在CoreData中。

應該做什麼......?請幫助...

而且,這是我現在的儲蓄數據:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { 
      return } 
let managedContext = appDelegate.persistentContainer.viewContext 
let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedContext) 
let category = NSManagedObject(entity: entity!, insertInto: managedContext) 

category.setValue(categoryName, forKeyPath: "categoryName") 
category.setValue(categoryId, forKey: "categoryId") 

    do { 

    try managedContext.save() 
    self.managedObject.append(category as! Category) 
    } catch let error as NSError { 
    print("Could not save. \(error), \(error.userInfo)") 
    } 
+1

請出示你的代碼更好的響應 –

+0

你保存管理對象範圍內? – Paulw11

+0

@ Paulw11數據是否應該被提取,以便在我訪問屏幕時顯示在桌面上...? –

回答

1

據我瞭解,你在coredata已輸入的舊數據是不可見的TableView,如果這是這種情況下,它正常工作,因爲TableView不會持久數據。數據保存在coreData中,您只需從Coredata中獲取數據並將其加載到TableView中即可。下面的代碼

使用來獲取

var category = [Category]() // Where Category = your NSManaged Class 

    var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category") 

    do { 
     category = try context.fetch(fetchRequest) as! [Category] 
    } catch { 
     fatalError("Failed to fetch category: \(error)") 
    } 

// Then you can use this array to populate UITableView Datasource and Call. 
arrTableView = category 
tableView.reloadData() 
+0

它不工作,@sudhir庫馬爾。第三行的語法看起來不合適。 –

+0

感謝您告訴我,我編輯了我的代碼。希望這個幫助 –

+0

似乎還有一個問題,@Sudhir kumar。此行拋出錯誤「arrTableView = category」,因爲具有tableview元素的數組是一種字符串,而'category'的類型是'Category'。將數組的字符串類型更改爲類型數組的數組會影響很多其他地方...... :( –