我确实经历过处理此问题的其他帖子。但是对于我的问题,我找不到多少。希望有人可以提供帮助。我的问题是......我想要在我的tableview
中显示某个已编辑的记录。为此,我想在Core-Data中更新该条目。我无法弄清楚如何做到这一点。
这就是我将编辑后的数据放入tableview并保存在Core Data中的方法。更新必须在两者之间的某个地方进行,但我无法确切地知道如何以及在哪里......?
@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)")
}
}
答案 0 :(得分:0)
File foo2 in some/path/foo0
File foo2 in some/path/foo1
File foo2 in some/path/foo2
内使用。这将确保在上下文的队列(线程)上执行上下文操作。context.performAndWait { }
func fetch() {
let request : NSFetchRequest< Category> = Category.fetchRequest()
//Predicate builds the where clause to filter records
//This is a sample, so edit based on your requirement
request.predicate = NSPredicate(format: "categoryID = %@", argumentArray: [10])
context.performAndWait {
do {
let categories = try context.fetch(request)
//Update
for category in categories {
category.name = "aaa"
}
}
catch {
print("error = \(error)")
}
}
}