gpt4 book ai didi

ios - 如何检查实体属性名称匹配,并重写(更新)其他属性的数据?

转载 作者:行者123 更新时间:2023-11-30 11:53:24 25 4
gpt4 key购买 nike

我正在使用带有属性的核心数据实体,这里是生成的子类代码:

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 数据并通过天气模型处理它,并使用此代码将数据保存到数据库中(效果很好):

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)"
}
}

关于ios - 如何检查实体属性名称匹配,并重写(更新)其他属性的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48105508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com