Swift - 核心数据学生信息存储应用程序错误

时间:2016-11-11 15:49:13

标签: swift core-data

编辑 - 我已经玩过代码;还有问题。

我一直在尝试修改本教程中的应用,以便我可以输入学生信息并使用核心数据进行存储。理想情况下,我希望能够在标签上显示该信息;但我还没到那么远。这是我第一次使用核心数据,目前,我已经碰壁,需要一些帮助,找出我的代码中哪些地方出了问题以及如何让它运转起来。

所以我的问题是,如何修复这些错误。 以及如何在标签上保存后显示所有数据。

Updated Screenshot Updated Error Screenshot

提前致谢!

代码:

import UIKit
import CoreData

class ViewController: UIViewController {

@IBOutlet var name: UITextField!
@IBOutlet var address1: UITextField!
@IBOutlet var address2: UITextField!
@IBOutlet var city: UITextField!
@IBOutlet var state: UITextField!
@IBOutlet var zip: UITextField!
@IBOutlet var grade: UITextField!


@IBOutlet var status: UILabel!



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

func getContext () -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}

@IBAction func insertStudent(_ sender: AnyObject) {
    let context = getContext()
    let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in: context)

    let contact = NSManagedObject(entity: entityDescription!, insertInto: context) as! Contacts

    contact.student_name = name.text
    contact.address1 = address1.text
    contact.address2 = address2.text
    contact.city = city.text
    contact.grade = grade.text
    contact.state = state.text
    contact.zip = zip.text

    var error: NSError?

    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

1 个答案:

答案 0 :(得分:0)

看起来你正试图混合使用Swift版本。请参阅下面的代码示例,看看这是否有助于解决问题。

<强>的AppDelegate

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "CDTest")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()



    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

在Swift 3中保存和从CoreData获取数据的函数。

func storeTranscription() {
    let context = getContext()

    //retrieve the entity that we just created
    let entity =  NSEntityDescription.entity(forEntityName: "ItemList", in: context)

    let transc = NSManagedObject(entity: entity!, insertInto: context) as! ItemList

    //set the entity values
    transc.itemID = Double(itemid)
    transc.productname = nametext
    transc.amount = Double(amountDouble)
    transc.stock = stockStatus
    transc.inventoryDate = inventoryDate

    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}

func getTranscriptions () {
    //create a fetch request, telling it about the entity
    let fetchRequest: NSFetchRequest<ItemList> = ItemList.fetchRequest()

    do {
        //go get the results
        let searchResults = try getContext().fetch(fetchRequest)
        fetchedStatsArray = searchResults as [NSManagedObject]
        //I like to check the size of the returned results!
        print ("num of results = \(searchResults.count)")
        //You need to convert to NSManagedObject to use 'for' loops
        for trans in searchResults as [NSManagedObject] {
            //get the Key Value pairs (although there may be a better way to do that...
            print("\(trans.value(forKey: "productname")!)")
            let mdate = trans.value(forKey: "inventoryDate") as! Date
            print(mdate)
        }

    } catch {
        print("Error with request: \(error)")
    }
}

您的代码转换为Swift 3

func getContext () -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    return appDelegate.persistentContainer.viewContext
}

@IBAction func insertStudent(_ sender: AnyObject) {
    let context = getContext()
    let entityDescription = NSEntityDescription.entity(forEntityName: "Contacts", in: context)

    let contact = NSManagedObject(entity: entityDescription!, insertInto: context) as! Contacts

    contact.student_name = name.text
    contact.address1 = address1.text
    contact.address2 = address2.text
    contact.city = city.text
    contact.grade = grade.text
    contact.state = state.text
    contact.zip = zip.text

    var error: NSError?

    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }

}