xcode 如何更新核心数据中的现有对象?[迅速]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32326523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update existing object in core data ? [Swift]
提问by sunny k
I have preloaded data from a .csv file into coredata. I am fetching the data in the following way
我已将 .csv 文件中的数据预加载到 coredata 中。我正在通过以下方式获取数据
var places:[Places] = []
in viewDidLoad
:
在viewDidLoad
:
if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
let fetchRequest = NSFetchRequest(entityName: "Places")
do{
places = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Places]
}
catch let error as NSError{
print("Failed to retrieve record: \(error.localizedDescription)")
}
}
In the data there is an attribute isFavorite of type String whose initial value is false. I am changing the value of isFavorite on button click. I want to save the changes made by the user. How can i make this change persistent ?
在数据中有一个字符串类型的属性 isFavorite,其初始值为 false。我正在更改按钮单击时 isFavorite 的值。我想保存用户所做的更改。我怎样才能使这种改变持久化?
Here is my button action
这是我的按钮操作
@IBAction func addToFavourites(sender: AnyObject) {
cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: 0)) as! CustomTableViewCell
if cell.isFavouriteLabel.text! == "false" {
cell.isFavouriteLabel.text = "true"
}else if cell.isFavouriteLabel.text == "true"{
cell.isFavouriteLabel.text = "false"
}
}
Basically i want to set the value of places.isFavourite = cell.isFavoriteLabel.text
and save to core data
基本上我想设置值places.isFavourite = cell.isFavoriteLabel.text
并保存到核心数据
EDIT: if i try this inside my button action method
编辑:如果我在我的按钮操作方法中尝试这个
if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
let place : Places = Places()
place.isFavourite = cell.isFavouriteLabel.text
do{
try managedObjectContext.save()
} catch let error as NSError{
print(error)
}
}
i am getting an error: Failed to call designated initializer on NSManagedObject class
我收到一个错误:无法在 NSManagedObject 类上调用指定的初始值设定项
if i simply add this code in the button action method
如果我只是在按钮操作方法中添加此代码
places.isFavourite = cell.isFavouriteLabel.text
i get this error: [Places] does not have a member named isFavourite
我收到此错误:[Places] 没有名为 isFavourite 的成员
采纳答案by MirekE
Your current code is:
您当前的代码是:
if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
let place : Places = Places()
place.isFavourite = cell.isFavouriteLabel.text
do{
try managedObjectContext.save()
} catch let error as NSError{
print(error)
}
}
That would create a new place (if it worked), but you need to update an existing one.
这将创建一个新位置(如果它有效),但您需要更新现有位置。
You have the places
returned from managedObjectContext.executeFetchRequest
.
您已从places
返回managedObjectContext.executeFetchRequest
。
So you need to get something like places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text
所以你需要得到类似的东西 places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text
and then managedObjectContext.save()
.
然后managedObjectContext.save()
。
回答by Bart Hopster
Use the save
function of the NSManagedObjectContext:
使用save
NSManagedObjectContext的功能:
places.isFavourite = cell.isFavoriteLabel.text
var error: NSError?
if managedObjectContext.save(&error) != true {
// Error
}
回答by Jér?me Demyttenaere
This is simple as this:
这很简单:
Find the entry you want to modify in
places
then save the core data context.func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. println("Unresolved error \(error), \(error!.userInfo)") abort() } } }
找到要修改的条目,
places
然后保存核心数据上下文。func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. println("Unresolved error \(error), \(error!.userInfo)") abort() } } }
I suggest you used a manager to insert, fetch and delete entry in your core data.
我建议您使用管理器在核心数据中插入、获取和删除条目。
import Foundation
import CoreData
class CoreDataHelper: NSObject {
class var shareInstance:CoreDataHelper {
struct Static {
static let instance:CoreDataHelper = CoreDataHelper()
}
return Static.instance
}
//MARK: - Insert -
func insertEntityForName(entityName:String) -> AnyObject {
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: self.managedObjectContext!)
}
//MARK: - Fetch -
func fetchEntitiesForName(entityName:String) -> NSArray {
...
}
//MARK: - Delete -
func deleteObject(object:NSManagedObject) {
self.managedObjectContext!.deleteObject(object)
}
// MARK: - Core Data Saving support -
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
Hop this can help you
跳这可以帮助你