我是一个Swift新手,正在建立一个核心数据应用程序。我已经构建并运行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 数组计数始终等于表中的行数。
但是,对于我的版本,它始终报告播放器数组的计数为零。因此,每次调用 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表并包含已定义的行。
答案 0 :(得分:0)
原始问题中没有包含类定义,因此:
var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
这与以下内容的定义不同:
let managedContext = appDelegate.persistentContainer.viewContext
然而我使用它们就好像它们是一样的。我将这两个标准化,所以它们是相同的,问题已经消失了。