Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.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
Ios Swift Core Data codegen:我的NSManagedObject没有有效的NSEntityDescription_Ios_Swift_Core Data - Fatal编程技术网

Ios Swift Core Data codegen:我的NSManagedObject没有有效的NSEntityDescription

Ios Swift Core Data codegen:我的NSManagedObject没有有效的NSEntityDescription,ios,swift,core-data,Ios,Swift,Core Data,更新1:我已经根据斯坦福大学下一堂课的内容修改了一些代码。我还删除了添加到AppDelegate的代码,因为我看到那里有名称冲突。错误消息保持不变。 我正在开发自己的iOS应用程序,同时遵循斯坦福大学通过Swift课程开发iOS 10应用程序。不过,我正在努力设置数据库。我已经为我遇到的问题创建了一个最小的示例。我正在尝试为数据库中的实体创建扩展。我正在尽最大努力学习本课程第10课幻灯片中的示例代码,因为我只需要完成这个简单的应用程序。然而,我遇到了一些障碍,促使我做出改变: 1) 虽然我被指示

更新1:我已经根据斯坦福大学下一堂课的内容修改了一些代码。我还删除了添加到AppDelegate的代码,因为我看到那里有名称冲突。错误消息保持不变。

我正在开发自己的iOS应用程序,同时遵循斯坦福大学通过Swift课程开发iOS 10应用程序。不过,我正在努力设置数据库。我已经为我遇到的问题创建了一个最小的示例。我正在尝试为数据库中的实体创建扩展。我正在尽最大努力学习本课程第10课幻灯片中的示例代码,因为我只需要完成这个简单的应用程序。然而,我遇到了一些障碍,促使我做出改变:

1) 虽然我被指示将模块设置为当前产品模块,但这不起作用(xcode无法通过这种方式找到文件),因此我将其设置为全局名称空间

2) 教授在他的示例中使用以下方法创建推特实体:

if let tweet = Tweet(context: context) {
    tweet.text = “some string”
    // more code
    }
但是这不起作用,xcode抱怨Tweet不是可选的(“条件绑定的初始值设定项必须具有可选类型”

撇开这些不谈,在我的例子中,我试图做一些非常简单的事情。我只是想建立一个CoreData数据库,并在其中添加一个条目。执行此操作时收到的错误消息是: “类为“database\u test.Subject”的NSManagedObject必须具有有效的NSEntityDescription。”

下面是我为测试此问题而生成的代码的一步一步:

1) 使用CoreData创建了一个新的Swift项目

2) 这是我的AppDelegate.swift

//
//  AppDelegate.swift
//  database_test
//

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

}
3) 创建了具有一个属性(uniqueID)的主题实体。这在全局命名空间()中。我为一个类别/扩展做代码生成。然后我创建Subject.swift并修复它以导入CoreData,并添加一些代码以添加唯一主题:

//
//  Subject.swift
//  database_test
//

import UIKit
import CoreData

class Subject: NSManagedObject {

    class func addSubject(adding newSubject: String, in context: NSManagedObjectContext) throws {
        let request: NSFetchRequest<Subject> = Subject.fetchRequest()
        request.predicate = NSPredicate(format: "uniqueID = %@", newSubject)
        do {
            let matches = try context.fetch(request)
            if matches.count > 0 {
                assert(matches.count==1, "Subject.addSubject - matches.count > 1")
            }
        } catch {
            throw(error)
        }

        let subject = Subject(context: context)
        subject.uniqueID = newSubject
    }

}
在模拟器中运行此命令时,我会遇到NSException类型的未捕获异常终止,该异常可追溯到由于未捕获异常“NSInvalidArgumentException”终止应用程序,原因是:“类为“database_test.Subject”的NSManagedObject必须具有有效的NSEntityDescription”。

//  Subject+CoreDataProperties.swift
//
//  This file was automatically generated and should not be edited.
//

import Foundation
import CoreData


extension Subject {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Subject> {
        return NSFetchRequest<Subject>(entityName: "Subject");
    }

    @NSManaged public var uniqueID: String?

}

//  database_test+CoreDataModel.swift
//
//  This file was automatically generated and should not be edited.
//

import Foundation
import CoreData
//
//  ViewController.swift
//  database_test
//
//  Created by Alex B on 2017-07-10.
//  Copyright © 2017 Alex B. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController {

    //let context = AppDelegate.viewContext
    var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer

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

    func testAdding(subjectID: String) {
        container?.performBackgroundTask { context in
            try?Subject.addSubject(adding: subjectID, in: context)
        }
    }

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


}