Ios 有人能看到我在用coreData保存事件时遗漏了什么吗?

Ios 有人能看到我在用coreData保存事件时遗漏了什么吗?,ios,swift,core-data,Ios,Swift,Core Data,我正在构建一个简单的应用程序,在其中我可以将膳食(食物)添加到列表中,然后使用UIPicker从另一个VC那里获取这些膳食。这很好,但我不能保存这个。(重新启动后不会保存任何数据)。我正在尝试使用coreData执行此操作,我可以在代码列表中看到事件/更改实际上正在保存和加载。(我已在其他应用程序中成功使用coreData) 有人能帮我吗?我该怎么办?我对IOS开发和Swift相当陌生,因此请明确具体=) 这是我的密码: 如果你还需要什么帮助,请告诉我。 非常感谢 VC 1: VC 2: App

我正在构建一个简单的应用程序,在其中我可以将膳食(食物)添加到列表中,然后使用UIPicker从另一个VC那里获取这些膳食。这很好,但我不能保存这个。(重新启动后不会保存任何数据)。我正在尝试使用coreData执行此操作,我可以在代码列表中看到事件/更改实际上正在保存和加载。(我已在其他应用程序中成功使用coreData)

有人能帮我吗?我该怎么办?我对IOS开发和Swift相当陌生,因此请明确具体=)

这是我的密码:

如果你还需要什么帮助,请告诉我。 非常感谢

VC 1:

VC 2:

AppDelegate:

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}

 // 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: "bonAPPetit")
        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)")
            }
        }
    }

}
coredataClass:

import UIKit
import CoreData

class coredataClass {

static var items = [MealsMenu]()

static let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


    static func saveItems(){

           do{
            try coredataClass.context.save()
               print("SAVED")
           }catch{
           print("Error saving context with")
           }

       }


    static func loadData(){
           let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()

           do{
            items = try coredataClass.context.fetch(request)
            print("LOADED")
           }catch{
               print("Error fetching data from context")
           }

       }
}
导入UIKit
导入CoreData
类coredataClass{
静态变量项=[MealsMenu]()
静态let上下文=(UIApplication.shared.delegate为!AppDelegate)。persistentContainer.viewContext
静态func saveItems(){
做{
尝试coredataClass.context.save()
打印(“已保存”)
}抓住{
打印(“保存上下文时出错”)
}
}
静态函数loadData(){
let请求:NSFetchRequest=MealsMenu.fetchRequest()
做{
items=try coredataClass.context.fetch(请求)
打印(“已加载”)
}抓住{
打印(“从上下文提取数据时出错”)
}
}
}

coreData类中的loadData方法在获取成功后不会返回项,因此,要么从该方法返回,要么在获取成功后使用闭包

 static func loadData()->[MealsMenu]{
           let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()

           do{
            items = try coredataClass.context.fetch(request)
            return items
            print("LOADED")
           }catch{
               print("Error fetching data from context")
            return items
           }

       }
static func loadData()->[MealsMenu]{
let请求:NSFetchRequest=MealsMenu.fetchRequest()
做{
items=try coredataClass.context.fetch(请求)
退货项目
打印(“已加载”)
}抓住{
打印(“从上下文提取数据时出错”)
退货项目
}
}

从视图控制器使用返回的值填充表视图数组

我意识到这不是一个答案,但是:核心数据在这方面是完全多余的。另外,使用一个只包含静态成员的类
coreDataClass
(以小写字母开始?)也是错误的。这可能是麻烦的原因。谢谢我不知道。我将尝试改为大写字母C!希望能解决它!在这种情况下,您会使用什么来代替CoreData?是的,我会的我说的不是类的拼写有问题,而是使用了一个只包含静态成员的类。这不是上课的方式。嗨,太好了,谢谢。我现在已经尝试过了,但我在尝试“加载数据”的任何地方都会收到这条消息。调用“loadData()”的结果未使用。我之前没有收到该消息,所以是否需要添加一些内容以使其正常工作?我在两个视图控制器上使用了那行“coredataClass.loadData()”,它们现在得到了这个消息。
import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}

 // 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: "bonAPPetit")
        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)")
            }
        }
    }

}
import UIKit
import CoreData

class coredataClass {

static var items = [MealsMenu]()

static let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


    static func saveItems(){

           do{
            try coredataClass.context.save()
               print("SAVED")
           }catch{
           print("Error saving context with")
           }

       }


    static func loadData(){
           let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()

           do{
            items = try coredataClass.context.fetch(request)
            print("LOADED")
           }catch{
               print("Error fetching data from context")
           }

       }
}
 static func loadData()->[MealsMenu]{
           let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()

           do{
            items = try coredataClass.context.fetch(request)
            return items
            print("LOADED")
           }catch{
               print("Error fetching data from context")
            return items
           }

       }