How to update existing object in core data ? [Swift]

后端 未结 3 1045
广开言路
广开言路 2020-12-21 08:49

I have preloaded data from a .csv file into coredata. I am fetching the data in the following way

var places:[Places] = []

in viewDi

3条回答
  •  隐瞒了意图╮
    2020-12-21 09:14

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

    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

提交回复
热议问题