如何更新核心数据中的现有对象?[迅速] [英] How to update existing object in core data ? [Swift]
问题描述
我已将 .csv 文件中的数据预加载到 coredata 中.我正在通过以下方式获取数据
I have preloaded data from a .csv file into coredata. I am fetching the data in the following way
var places:[Places] = []
在 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)")
}
}
在数据中有一个字符串类型的属性isFavorite,它的初始值为false.我正在更改按钮单击时 isFavorite 的值.我想保存用户所做的更改.我如何才能使这种更改持久化?
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 ?
这是我的按钮操作
@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"
}
}
基本上我想设置 places.isFavourite = cell.isFavoriteLabel.text
的值并保存到核心数据
Basically i want to set the value of places.isFavourite = cell.isFavoriteLabel.text
and save to core data
编辑:如果我在我的按钮操作方法中尝试这个
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)
}
}
我收到一个错误:无法在 NSManagedObject 类上调用指定的初始值设定项
i am getting an error : Failed to call designated initializer on NSManagedObject class
如果我只是在按钮操作方法中添加此代码
if i simply add this code in the button action method
places.isFavourite = cell.isFavouriteLabel.text
我收到这个错误:[Places] 没有名为 isFavourite 的成员
i get this error : [Places] does not have a member named isFavourite
推荐答案
您当前的代码是:
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.
您拥有从 managedObjectContext.executeFetchRequest
返回的 places
.
You have the places
returned from managedObjectContext.executeFetchRequest
.
所以你需要得到类似 places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text
然后managedObjectContext.save()
.
这篇关于如何更新核心数据中的现有对象?[迅速]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!