我正在使用带有属性的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()
}
问题是......如何检查城市名称的重合(名称属性)?如果这样的城市已经存在于数据库中,而不是创建新记录,则覆盖(更新)当前属性(description,temp,temp_max,temp_min)的值?谢谢。
您只需要尝试获取现有对象。如果获取成功,则更新其属性。如果未找到匹配项,则创建一个新对象。就像是:
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)"
}
}