【发布时间】: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