Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift-核心数据学生信息存储应用程序错误_Swift_Core Data - Fatal编程技术网

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

Swift-核心数据学生信息存储应用程序错误,swift,core-data,Swift,Core Data,编辑-我已经玩弄了代码;还有问题 在本教程中,我一直在尝试修改应用程序,以便输入学生信息并使用核心数据存储。理想情况下,我希望能够在标签上显示该信息;但我还没走那么远。这是我第一次使用核心数据,目前,我遇到了困难,需要一些帮助来找出我的代码哪里出了问题,以及如何让它工作 因此,我的问题是,如何修复这些错误。 在保存到标签上之后,我如何显示所有数据 提前谢谢 代码: import UIKit import CoreData class ViewController: UIViewContro

编辑-我已经玩弄了代码;还有问题

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

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

提前谢谢

代码:

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.
}


}

看起来您正在尝试混合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重新编写代码了吗?你向我推荐的代码让我不知所措,我不知道该如何修改你的建议。@cisco21我在回答中添加了你更正的代码。另外,如果你说这是一个新项目,那么你的appDelegate应该已经和我的答案中的一样了。关于未解析标识符“NSEntityDescription”和“NSManagedObject”在导入UIKit下面添加导入CoreData,我收到了大量错误。我已经更新了我的帖子,更新了屏幕截图(请查看它们)。基本上,我重播了这个项目,但仍然收到了这些错误。请看我的代码,看看是否正确。我认为这与我在第一张截图中创建的实体有关。请看一下右边,类名附近,等等,看看我是否应该修改一些东西来减轻这些错误。顺便再次感谢你的帮助。
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 {

    }

}