簡體   English   中英

在Tableview中更新條目(編輯后)並在Tableview中顯示時出現問題

[英]Issue with updating entries in tableview (after editing)and showing in Tableview

這是我的情況...單擊導航欄右上角的加號按鈕時,將出現一個帶有文本字段的Alertview,然后在文本字段中添加一些數據,然后按OK按鈕。 這導致文本字段中的數據顯示在表格視圖中,並且也存儲在核心數據中。

然后,當我單擊現在具有來自alertview文本字段的數據的行時,我轉到另一個要編輯的視圖。 viewcontroller具有一個文本字段,該字段具有上一屏幕行中的值。 現在,我單擊文本字段並編輯它的值,然后按右上角的保存。 現在,理想情況下,當我按保存並轉到上一個屏幕時,現在應該在表格視圖中看到已編輯的值,而不是原來的值。

但是發生的是,當我按保存並返回上一屏幕時,我暫時在tableviewcontroller看到更新的值。 但實際上,該值在核心數據添加兩次,當我回去從這個tableview一些其他視圖,並返回到它,然后我看到不僅是編輯也是新編輯的值是之前存在的價值加了兩次! 我無法理解這種行為。

在編輯屏幕中單擊“保存”按鈕時,這就是我正在做的...

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "save" {
            editedModel = editTextField.text
    }
}

回到表視圖屏幕,這就是我正在做的...(在tableviewcontroller屏幕中)

@IBAction func saveToMainEditViewController (segue:UIStoryboardSegue) {
    let detailViewController = segue.source as! EditCategoriesTableViewController
    let index = detailViewController.index
    let modelString = detailViewController.editedModel //Edited model has the edited string

    let myCategory1 = Category(context: self.context)
    myCategory1.categoryName = modelString
    mangObjArr[index!] = myCategory1     

    //Saving to 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(myCategory1.categoryName, forKeyPath: "categoryName")
    category.setValue(myCategory1.categoryId, forKey: "categoryId")
    do {

        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
    categoryTableView.reloadData()

}

在cellForRowAtIndexPath中,這就是我正在做的...

    let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)

    let person = mangObjArr[indexPath.row]
    cell.textLabel?.text = person.categoryName
    return cell

您要插入新記錄,而不是更新前一個記錄
在對Category實體進行任何插入之前,編寫一段代碼,以當前名稱獲取記錄,然后用編輯后的字符串替換其當前名稱,然后保存。
此代碼使用舊名稱獲取記錄,並用新名稱替換其名稱

let fetchRequest : NSFetchRequest<Category> = Category.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "(categoryName == %@)", argumentArray: [*Your current categoryName*])
 do {
     let result = try managedContext.fetch(fetchRequest)
     if let toBeUpdatedRecord = result.first
     {
        toBeUpdatedRecord.categoryName = newName
        //here you should save 
     }
} catch{}

暫無
暫無

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

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