gpt4 book ai didi

ios - 使用 CoreData 和 Swift 2.0 保存问题

转载 作者:可可西里 更新时间:2023-11-01 05:20:16 25 4
gpt4 key购买 nike

问题

我试图简单地保存一条记录然后获取它,但我认为我在这里做错了,因为我的记录没有保存。输出窗口只显示一个空数组。

我在 Xcode 7 beta 5 中使用 boiler-plate AppDelegate CoreData 堆栈。[See Gist Here]

尝试

实体

enter image description here

型号

import Foundation
import CoreData

// @func(Person) edit: removed
class Person: NSManagedObject {

@NSManaged var firstName: String?
@NSManaged var lastName: String?
}

View Controller

import UIKit
import CoreData

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
seedPerson()
fetch()
}

func seedPerson() {

let managedContext = AppDelegate().managedObjectContext

let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

// add our data
person.setValue("Dan", forKey: "firstName")
person.setValue("Beaulieu", forKey: "lastName")

// save it
do {

try AppDelegate().managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}

func fetch() {
let moc = AppDelegate().managedObjectContext
let personFetch = NSFetchRequest(entityName: "Person")

do {
let fetchedPerson = try moc.executeFetchRequest(personFetch) as! [Person]
print(fetchedPerson.first!.firstName)


} catch {
fatalError("Failed to fetch person: \(error)")
}
}
}

期望的行为

我要返回的是数据存储中我的名字,但我认为我的记录从未保存过,这就是为什么我得到的是一个空数组。

所以我的具体问题是,如何使用样板核心数据堆栈进行保存?

最佳答案

问题是我正在创建一个新的 managedObjectContext 实例并试图保存到它,这显然是行不通的,因为我正在使用我在方法顶部创建的托管上下文。

func seedPerson() {

let managedContext = AppDelegate().managedObjectContext

//let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

//let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedContext)

// add our data
person.setValue("Dan", forKey: "firstName")
person.setValue("Beaulieu", forKey: "lastName")

// save it
do {
// this was the problem ///////////////
try managedContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}

视频

我已经上传了一个关于如何在 swift 2 中设置核心数据的视频教程:https://www.youtube.com/watch?v=WcQkBYu86h8

关于ios - 使用 CoreData 和 Swift 2.0 保存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896933/

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