gpt4 book ai didi

ios - 尽管表不为空,核心数据获取仍返回零记录

转载 作者:行者123 更新时间:2023-11-30 12:41:45 41 4
gpt4 key购买 nike

我是 Swift 新手,正在构建一个 Core Data 应用程序。我已经构建并运行了 sample app from Ray Wenderlich's site其按预期工作。

我从 Ray 的应用程序中提取并修改了以下摘录:

var people: [NSManagedObject] = []

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

//1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}

let managedContext = appDelegate.persistentContainer.viewContext

// 2
let fetchrequest = NSFetchRequest<NSManagedObject>(entityName: "Person")

// 3
do {
people = try managedContext.fetch(fetchrequest)
print("\(people.count) fetched from Person")
}
catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}

这按预期工作。但是,以下是我在我的应用程序中实现的内容:

var players: [NSManagedObject] = []

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}

let managedContext = appDelegate.persistentContainer.viewContext

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Golfer")

do {
players = try managedContext.fetch(fetchRequest)

print("\(players.count) fetched from Golfer")
// Load any saved players, otherwise load sample data.
if players.count == 0 {
// Load the sample data.
// There are no players to load
os_log("Loading sample players", log: OSLog.default, type: .debug)
loadSamplePlayers()
}
}
catch let error as NSError {
print("Could not fetch Golfers. \(error), \(error.userInfo)")
}
}

示例代码始终返回 Person 表的完整结果,并且 person 数组计数始终等于表中的行数。

但是,对于我的版本,它总是报告players数组的计数为零。因此,每次都会调用 loadSamplePlayers() 方法(将三个样本记录添加到 Golfer 表中)。

使用 SQL Lite 数据库检查器,我可以看到 Golfer 表在每次调用应用程序后继续增长。

我很困惑为什么这两个几乎相同的代码示例应该表现不同。

任何见解将不胜感激。

谢谢!

编辑:

这是还引用的 loadSamplePlayers() 方法和 printDatabaseStats():

private func loadSamplePlayers() {

let sampleFirstNames: [String] = ["Casper", "Jocelyn", "Arthur"]
let sampleLastNames: [String] = ["Vitturio", "Brown", "Mullard"]
let sampleEmails: [String] = ["a@b.com", "fred@x.co.uk", "last@ohm.com"]
let sampleHandicaps: [Double] = [16.2, 6.4, 27.2]

let entity = NSEntityDescription.entity(forEntityName: "Golfer", in: managedObjectContext!)!

for i in 1...3 {
let player = NSManagedObject(entity: entity, insertInto: managedObjectContext)

player.setValue(sampleFirstNames[i-1], forKeyPath: "firstName")
player.setValue(sampleLastNames[i-1], forKey: "lastName")
player.setValue(sampleEmails[i-1], forKey: "emailAddress")
player.setValue(sampleHandicaps[i-1], forKey: "exactHandicap")
// player.setValue(sampleMugshots[i-1], forKey: "mugShot")

print("Prepare to save")

do {
try managedObjectContext?.save()
players.append(player)
}
catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}

print("There are now \(printDatabaseStats()) in the Golfers table")
}
}

private func printDatabaseStats() -> Int {
var count = 0
managedObjectContext?.performAndWait {
if let golferCount = try? self.managedObjectContext!.count(for: NSFetchRequest(entityName: "Golfer")) {
print("\(golferCount) Payers")
count = golferCount
}
}

return count
}

这似乎工作成功,因为 print(...) 方法生成预期的控制台消息,并且 Golfer 表已填充并包含定义的行。

最佳答案

原始问题中未包含类定义,因此:

var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext

这与以下定义不同:

let managedContext = appDelegate.persistentContainer.viewContext

但我使用它们就好像它们是一样的。我将两者标准化,因此它们是相同的,问题就消失了。

关于ios - 尽管表不为空,核心数据获取仍返回零记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42161215/

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