【问题标题】:How to update existing object in core data ? [Swift]如何更新核心数据中的现有对象? [迅速]
【发布时间】:2015-11-26 09:21:15
【问题描述】:

我已将 .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 的成员

【问题讨论】:

    标签: ios iphone xcode swift core-data


    【解决方案1】:

    使用 NSManagedObjectContext 的save 函数:

    places.isFavourite = cell.isFavoriteLabel.text
    
    var error: NSError?
    if managedObjectContext.save(&error) != true {
        // Error
    }
    

    【讨论】:

    • 我似乎无法在我的按钮操作方法中使用 places.isFavourite 访问 isFavourite
    • 取决于您的实现,您应该能够在单击按钮后访问相应的 Places 对象。您的按钮操作方法有一个sender 参数,也许您可​​以使用它。
    • 我可以访问 isFavorite 如果地方是这样声明的var places : Places!
    【解决方案2】:

    这很简单:

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

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      您当前的代码是:

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

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

      您有从managedObjectContext.executeFetchRequest 返回的places

      所以你需要得到类似places[index_of_the_cell_in_question].isFavourite = cell.isFavouriteLabel.text的东西

      然后是managedObjectContext.save()

      【讨论】:

      • thanx places[sender.tag].isFavourite = cell.isFavouriteLabel.text 成功了
      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多