简体   繁体   English

使用Swift更新实体记录而不是使用CoreData创建新记录

[英]Updating an entity record instead of creating a new record with CoreData using Swift

I need to fetch some information from the server. 我需要从服务器获取一些信息。
and then I need to save them using CoreData. 然后我需要使用CoreData保存它们。
The problem is that the same record with same attributes is saved several times. 问题是具有相同属性的相同记录会被保存多次。
I want to save just new records to the CoreData and update the existing ones. 我只想将新记录保存到CoreData并更新现有记录。

func saveChanges() throws {
        var error: ErrorType?
        mainQueueContext.performBlockAndWait () {
            if self.mainQueueContext.hasChanges {
                do {
                    try self.mainQueueContext.save()
                } catch let saveError {
                    error = saveError
                }
            }
        }
        if let error = error {
            throw error
        }
   }

func fetchRecentPosts(completion completion: (PostResult) -> Void){

   .
   .
   .
   do{
        try self.coreDataStack.saveChanges()
        print("now data is saved in this device")

   }
   catch let error {
        result = .Failure(error)
   }
   .
   .
   .
}

My idea is to check if that id was saved. 我的想法是检查该id已保存。 If it was saved before I should not add another record. 如果已保存,则不应添加其他记录。 Then how can I update the existing one? 那我该如何更新现有的呢? And is it a good way to solve this problem? 这是解决此问题的好方法吗?

First check if your record exists in DB 首先检查您的记录是否存在于数据库中

static func getMyRecord(with id : String, context : NSManagedObjectContext) -> MyRecord? {
            let fetchRequest: NSFetchRequest< MyRecord> = MyRecord.fetchRequest()
            fetchRequest.predicate = NSPredicate(format: "id = %@", id)
            let foundRecordsArray = try! context.fetch(fetchRequest)
            if foundRecordsArray.count > 0 {
                return foundRecordsArray[0]
            }
            return nil
        }

While inserting if available update it else create new record. 插入时(如果可用)更新,否则将创建新记录。

static func insertRecord(_ record : MyRecord, context : NSManagaedObjectContext) {
    let foundRecord = DataInserterClass. getMyRecord(with: yourID, context: context)
            if foundRecord == nil {
                //create new record
            }
            else {
                //update foundRecord
            }
            try! context.save()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM