I'm trying to simply save a record and then fetch it but I think I'm doing something wrong here as my record isn't saving. The output window just shows an empty array.
I'm using the boiler-plate AppDelegate CoreData stack in Xcode 7 beta 5. [See Gist Here]
Entity
Model
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)")
}
}
}
What I'm trying to return is my first name from the data store, however I don't think my record is ever saved which is why I'm getting is an empty array.
So my specific question is, how do I save using the boiler plate core data stack?
The problem was that I was creating a new instance of managedObjectContext and trying to save to it which obviously wouldn't work because I was working with the managed context that I created at the top of my method.
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)")
}
}
I've uploaded a video tutorial on how to setup core data in swift 2 : https://www.youtube.com/watch?v=WcQkBYu86h8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With