简体   繁体   中英

Simple Fetch in Swift 3 Core Data

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.

这是有效的:

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

try doing it in moc context like this

@IBOutlet weak var inValue: UITextField!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
@IBAction func goBtn(_ sender: UIButton) {
    var inVal = Int(inValue.text!)!
    for i in inVal...inVal + 10 {
     context.perform {
         let nums = NSEntityDescription.insertNewObject(forEntityName: "Numbers", into: self.context) as! Numbers
            let request:NSFetchRequest<Numbers> = Numbers.fetchRequest()
            request.predicate = NSPredicate(format: "nums == %d", i)
            do { let numbers =  try? request.execute()
                if (numbers?.count)! > 0 {
                    print ("Value \(i) alreayd existis")
                } else {
                    nums.nums = Decimal(i) as NSDecimalNumber?
                }
              } catch let error {
                print ("Error while fetching \(error)")
            }
        }

        do {
            try self.context.save()
            print ("Value stored in DB \(i)")
        } catch let error {
            print ("Error while saving \(error)")
        }
    }
}

尝试:

    let personFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM