如何更新核心数据中的现有对象? [迅速]

时间:2015-09-01 08:03:23

标签: ios iphone xcode swift core-data

我已将.csv文件中的数据预加载到coredata中。我按以下方式获取数据

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)")
            }
        }

在数据中有一个属性为String的属性isFavorite,其初始值为false。我正在点击按钮更改isFavorite的值。我想保存用户所做的更改。 如何才能使此更改持久?

这是我的按钮操作

@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的值并保存到核心数据

编辑:如果我在我的按钮操作方法

中尝试此操作
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类上调用指定的初始化程序

如果我只是在按钮操作方法中添加此代码

places.isFavourite = cell.isFavouriteLabel.text

我收到错误:[Places]没有名为isFavourite的成员

3 个答案:

答案 0 :(得分:2)

您当前的代码是:

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)

            }
          }

这将创建一个新的地方(如果它有效),但您需要更新现有的地方。

您从places返回了managedObjectContext.executeFetchRequest

所以你需要得到像places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text

这样的东西

然后managedObjectContext.save()

答案 1 :(得分:0)

使用NSManagedObjectContext的save功能:

places.isFavourite = cell.isFavoriteLabel.text

var error: NSError?
if managedObjectContext.save(&error) != true {
    // Error
}

答案 2 :(得分:0)

这很简单:

  • 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()
            }
        }
    }
    

我建议您使用管理器在核心数据中插入,获取和删除条目。

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()
            }
        }
    }

跳这可以帮助你