Simple Fetch in Swift 3 Core Data

Fourthdan picture Fourthdan · Sep 7, 2016 · Viewed 8.4k times · Source

I've been trying to implement a simple core data functionality within my app so that it shows a tutorial (a separate view controller with a scroll page) only the first time the app loads, and bypasses it every other time. I started with syntax from CoreData tutorials for Swift 2, but then had to tweak based on Swift 3's auto corrections and other tutorials that helped me overcome the errors i found along the way (such as SIGBRT). The current problem I'm having is a EXC_BAD_INSTRUCTION error, which I need help fixing.

I've got a scrollViewController with the following code:

class ScrollViewController: UIViewController, NSFetchedResultsControllerDelegate {

@IBOutlet var mainScrollView: UIScrollView!

@IBOutlet weak var endTutorial: UIButton!

var imageArray = [UIImage]()

class Person: NSManagedObject {
    @NSManaged var tutorialstatus: String?
}

func seed() {
    let moc = DataController().managedObjectContext
    let entityDes = NSEntityDescription.entity(forEntityName: "Person", in: moc)
    let entity = Person(entity: entityDes!, insertInto: moc)
    entity.tutorialstatus="test value"
    do {
        try moc.save()
    } catch {
        fatalError("Failure to save context: \(error)")
    }
}

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


    do {
        let fetchedPerson = try moc.fetch(personFetch)
        print(fetchedPerson.first!.tutorialstatus)

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

At the let fetchedPerson = try moc.fetch(personFetch) line, when I try to compile, I see the error EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)

I am using Xcode 8, Beta 8. I have a swift file called 'CoreDataStuf.xcdatamodeld which has an entity named "Person" with an attribute called tutorialstatus, which is a string. I've also given that entity a class of Person. I also have a DataController.swift file where i refer to the URL CoreDataStuf.

Answer

Fourthdan picture Fourthdan · Sep 9, 2016

This is what worked:

let fetchedPerson = try moc.fetch(personFetch as! NSFetchRequest<NSFetchRequestResult>)