ios - 覆盖核心数据值

标签 ios iphone swift core-data

你好,我需要覆盖 CoreData 上的值(如果已经存在)。例如,如果已经在 CoreData 我有 Josh 我需要删除它,然后保存新的 Josh

func save(value:String, forkey:String) {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "Lastname", in: context)

    let add = NSManagedObject(entity: entity!, insertInto: context)
    add.setValue(value, forKey: forkey)

    do {
        try context.save()
        print("save ->  \(value)")
    } catch {
        print("err \(error)")
    }
}

最佳答案

我们可以检查值是否存在。然后在数据库中更新和创建值

class func checkAndUpdateAtIndex(entry_id: String, comment_text: String, comment_name: String, comment_pic: String, comment_date: String, comment_id: String, comment_isDeleted: String, comment_userid: String) {
    let context: NSManagedObjectContext = DataAccess.shared.managedObjectContext
    let request = NSFetchRequest(entityName: "Comment")
    request.predicate = NSPredicate(format: "comment_id = %@", comment_id)

    if let fetchResults = (try? DataAccess.shared.managedObjectContext.executeFetchRequest(request)) as? [NSManagedObject] {
        if fetchResults.count != 0{
            //update value
            var managedObject = fetchResults as! [Comment]
            managedObject[0].setValue(entry_id, forKey: "entry_id")
            managedObject[0].setValue(comment_text, forKey: "comment_text")
            managedObject[0].setValue(comment_name, forKey: "comment_name")
            managedObject[0].setValue(comment_pic, forKey: "comment_pic")

        }else {  
            // create new entity if not found
            let newItems = NSEntityDescription.insertNewObjectForEntityForName("Comment", inManagedObjectContext: context) as! Comment

            newItems.entry_id = entry_id
            newItems.comment_text = comment_text
            newItems.comment_name = comment_name
            newItems.comment_pic = comment_pic            
        }


            do {
                try context.save()
            } catch {}
    }
}

在此 Update 方法中,我首先获取我们要更新的实体,然后将新值存储在该位置。

关于ios - 覆盖核心数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42294358/

相关文章:

ios - Xamarin.iOS UITableView,如何强制单元格更新?

iphone - 整个应用程序中的异常处理

ios - 为什么我的 "if"语句评估错误即使一切都是正确的

ios - 使用来自 API 的 JSON 填充单元格

ios - 使用流式布局,还是自定义?

ios - 错误ITMS- 90035无效签名

swift - UITextView,订单号与标题和内容之间的距离 - Swift

iphone - Swift 隐藏后无法显示后退按钮

ios - 带有@Binding可选属性的SwiftUI View的初始化似乎模棱两可

ios - 如何在 ios 7 和 ios6 中显示启动图像