gpt4 book ai didi

ios - swift:检查核心数据中的记录

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

有没有办法从 Xcode 检查核心数据?

我创建了两个函数(写入数据库,从数据库读取),它们不会失败,但读取在应该返回写入数据时返回空数组。

功能:

func writeData () {
appDel = UIApplication.sharedApplication().delegate as! AppDelegate
context = appDel.managedObjectContext

let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject

let timestamp = NSDate()

for geo in geoArray {

//geoArray - array of dictionaries ([CountryName: "Lithuania", TelCode: 370],[CountryName: "Belarus", TelCode: 375],[CountryName: "Latvia", TelCode: 371])
//geo - Dictionary of tipe <String: AnyObject>
// CoreData: countryName type is String

newRecord.setValue(timestamp, forKey: "dateUploaded")
newRecord.setValue(String(geo["CountryName"]!), forKey: "countryName")

do {
try context.save()
print("Saved successfully")
} catch _ {
print("there was issue saving data!")
}

}


}







func loadData(country: String) {
appDel = UIApplication.sharedApplication().delegate as! AppDelegate
context = appDel.managedObjectContext


results = [AnyObject]()

let request = NSFetchRequest(entityName: "CountryList")
request.resultType = NSFetchRequestResultType.DictionaryResultType

request.predicate = NSPredicate(format: "countryName = %@", country)



let sort1 = NSSortDescriptor(key: "dateUploaded", ascending: true)

request.sortDescriptors = [sort1]

do {
results = try context.executeFetchRequest(request)
print(results!)

} catch _ {
print ("error trying to fetch!")
}
}

我想从 Xcode 检查我的 CoreData 实体中是否有任何记录。那可能吗?

谢谢

最佳答案

您实际上是在循环内更改相同的核心数据对象。因此,最终在循环结束时,您将只剩下一个具有数组中最后一个国家/地区名称的对象。您应该每次都在循环内创建一个 newRecord

将此行移到 for 循环内,它应该可以正常工作。

let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject

请注意,您正在创建一个核心数据管理对象并在循环内更改它,并且保存会多次保存同一对象。如果要保存多个对象,则必须每次创建一个新对象,设置其值,然后保存。您还可以将保存部分移到循环之外。

func writeData () {
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let timestamp = NSDate()
for geo in geoArray {
let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject
newRecord.setValue(timestamp, forKey: "dateUploaded")
newRecord.setValue(String(geo["CountryName"]!), forKey: "countryName")
}
do {
try context.save()
print("Saved successfully")
} catch _ {
print("there was issue saving data!")
}

}

关于ios - swift:检查核心数据中的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36169776/

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