(iOS Swift)从Core Data获取记录会返回致命错误或为零

时间:2016-07-10 04:27:08

标签: ios iphone swift core-data

我开始使用Swift为iPhone应用程序编码,我正面临着这个相当令人困惑的障碍,对于你们中的一些人来说可能是微不足道的。我一直收到错误消息,记录是fatal error: unexpectedly found nil while unwrapping an Optional valuenil,但是当我检查.sqlite时,记录就在那里

让我带你走过

我的.xcdatamodeld的名称是ReviewerApp.xcdatamodeld,与我的应用名称ReviewApp相同 ReviewerApp.xcdatamodeld

我的班级名称为Users,我的实体名称为User

Class: Users, Entity: User

我的属性(用户名,电子邮件,密码)全部为type: Stringproperties: optional

Users.swift

import Foundation

import CoreData

@objc(Users)

class Users: NSManagedObject {

    // Insert code here to add functionality to your managed object subclass

   @NSManaged var username: String?

   @NSManaged var email: String?

   @NSManaged var password: String?


}

saveUser()

中的signUpController.swift功能
func saveUser() {

    // create an instance of our managedObjectContext
    let moc = DataController().managedObjectContext

    // we set up our entity by selecting the entity and context that we're targeting
    let entity = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: moc) as! Users

    // add our data
    entity.setValue(usernameTxtFld.text, forKey: "username")
    entity.setValue(emailTxtFld.text, forKey: "email")
    entity.setValue(passwordTxtFld.text, forKey: "password")

    // we save our entity
    do {
        try moc.save()
        //user.append(entity)
        print("saved")
    } catch {
        fatalError("Failure to save context: \(error)")
    }

}

fetch()

中的SignInController.swift功能
let moc = DataController().managedObjectContext    
let userFetch = NSFetchRequest(entityName: "User")           
do {    
    let fetchedUser = try moc.executeFetchRequest(userFetch) as! [Users]    
    print(fetchedUser.first!.username!)               
 } catch {
    fatalError("Failed to fetch person: \(error)")  
 }

每次我保存用户注册过程时,记录都会保存在核心数据中。但每次我试图获取它:

  1. by:print(fetchedUser.first!.username!),控制台中的消息为fatal error: unexpectedly found nil while unwrapping an Optional value

  2. by:print(fetchedUser.first?.username),控制台中的消息为nil

  3. 非常感谢您的帮助,提前

3 个答案:

答案 0 :(得分:0)

首先我强烈建议你不要使用'!'代码中的任何位置都会导致应用程序崩溃(仅限静态资源)。您可以使用'if let XXX = YYY as? [...]'安全地施展任何你想要的东西......

然后您可能没有在数据库中保存任何内容。你的模特怎么样?您的用户类必须适合您构建的模型,否则它将无法工作(这是一种痛苦),在您的模型中,您必须为您的实体提供其类(在“父实体”下面的“类”字段中)

此外,您不必在事先投放实体时使用'entity.setValue(usernameTxtFld.text,forKey:“username”)'。你可以只是'entity.username = usernameTxtFld.text'。

如果我没有帮助,请尝试添加xcdatamodel。

答案 1 :(得分:0)

我想你错过了

 let entityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: moc)

fetchRequest.entity = entityDescription

do {
    let fetchedUser = try moc.executeFetchRequest(fetchRequest)
      print(fetchedUser.first!.username!)
} catch {
    let fetchError = error as NSError
    print(fetchError)
}

如果获取请求成功,则该方法返回结果数组。请注意,如果获取请求成功,Core Data始终返回一个数组,即使我们期望一个结果或者Core Data没有找到任何匹配的记录。

有关详细信息和说明,请访问 -

http://code.tutsplus.com/tutorials/core-data-and-swift-managed-objects-and-fetch-requests--cms-25068

答案 2 :(得分:0)

案件已经结案。 DataController.swift存在一些问题。它被调用来保存数据,但是当它被调用来获取数据时,它会以某种方式指向不同的地方。所以,我做的是

  1. 不再使用DataController.swift
  2. 我的AppDelegate.swift配备了// MARK: - Core Data Saving支持保存上下文,因为我没有设置我的应用程序包含核心数据在开头

    func saveContext(){

        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
    
  3. 我将保存功能更改为

    func saveUser(){

        let appDelegate =
            UIApplication.sharedApplication().delegate as! AppDelegate
    
        let managedContext = appDelegate.managedObjectContext
    
        //2
        let entity = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: managedContext) as! Users
    
    
        //3
        entity.setValue(usernameTxtFld.text, forKey: "username")
        entity.setValue(emailTxtFld.text, forKey: "email")
        entity.setValue(passwordTxtFld.text, forKey: "password")
    
        //4
        do {
            try managedContext.save()
            //5
            message = "Signing up is successful"
            alertMessage(message)
    
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    
    
    }
    
  4. 并将我的获取功能更改为

    func fetch(){

        let appDelegate =
            UIApplication.sharedApplication().delegate as! AppDelegate
    
        let managedContext = appDelegate.managedObjectContext
    
        //2
        let fetchRequest = NSFetchRequest(entityName: "Users")
    
        let predicate = NSPredicate(format: "email == %@ AND password == %@", emailTxtFld.text!, passwordTxtFld.text!)
        fetchRequest.predicate = predicate
        //3
        do {
            let results =
                try managedContext.executeFetchRequest(fetchRequest)
            user = results as! [Users]
    
            let row = user.count
    
            if row > 0 {
    
                message = "You're signed in"
                //self.performSegueWithIdentifier("signInIdentifier", sender: self)
            }else{
    
                message = "Email & password combination is incorrect!"
            }
    
            alertMessage(message)
    
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    
    
    }