【问题标题】:How to check the entity attribute name match, and rewrite(update) data for another attributes?如何检查实体属性名称匹配,并为其他属性重写(更新)数据?
【发布时间】:2018-01-05 00:21:19
【问题描述】:

我正在使用带有属性的Core Data实体,这里是生成的子类代码:

extension City {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<City> {
        return NSFetchRequest<City>(entityName: "City")
    }
    @NSManaged public var name: String?
    @NSManaged public var description: String?
    @NSManaged public var temp: Double
    @NSManaged public var temp_max: Double
    @NSManaged public var temp_min: Double
}

我正在解析 JSON 数据并通过 Weather 模型对其进行处理,并使用此代码将数据保存到数据库中(效果很好):

func saveWeatherData() {

        let ad = UIApplication.shared.delegate as! AppDelegate
        let context = ad.persistentContainer.viewContext

        let city = City(context: context)

        city.name = Weather.locationName!

        city.description = Weather.details!

        city.temp = Weather.temp

        city.temp_min = Weather.tempMin

        city.temp_max = Weather.tempMax

        ad.saveContext()
    }

问题是......如何检查城市名称(名称属性)的一致性?如果数据库中已经存在这样的城市,而不是创建新记录,而是覆盖(更新)当前属性的值(描述、临时、临时最大、临时最小)? 谢谢。

【问题讨论】:

  • 您需要先尝试获取可能匹配的城市,如果不存在则创建一个新城市。
  • 我正在获取现有数据,但是如果我有匹配项,如何更新属性值??
  • 只需更新您检索到的City 的属性并保存上下文。
  • 我不确定我的 fetchRequest 代码,您能否举一个代码示例,在这种情况下如何尝试获取潜在的匹配城市并在它不存在时创建一个新城市?

标签: ios swift core-data nsmanagedobjectcontext


【解决方案1】:

您只需要尝试获取现有对象。如果获取成功,则更新其属性。如果未找到匹配项,则创建一个新对象。比如:

func saveWeatherData() {

    let ad = UIApplication.shared.delegate as! AppDelegate
    let context = ad.persistentContainer.viewContext

    let fetchRequest:NSFetchRequest<City> = City.fetchRequest()
    fetchRequest.predicate = NSPredicate(format:"name = %@",Weather.locationName)

    fetchRequest.fetchLimit = 1  

    do {
       let result = try context.fetch(fetchRequest)
       let city = result.first ?? City(context: context)

       city.name = Weather.locationName!
       city.description = Weather.details!
       city.temp = Weather.temp
       city.temp_min = Weather.tempMin
       city.temp_max = Weather.tempMax

       ad.saveContext()
    }
    catch {
        print("Error fetching city: \(error.localizedDescription)"
    }
}

【讨论】:

  • @rurom,如果我的回答对你有帮助,如果你能通过点击旁边的勾号接受它,我将不胜感激。
猜你喜欢
  • 2015-08-28
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多