未申报的类型' NSPersistenContainer'

时间:2017-04-14 15:14:36

标签: ios swift xcode core-data

我在我的Xcode项目(Swift 2.2和Xcode 7.2.1)中插入Appdelegate文件到CoreData的代码。

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

    func saveContext () {
        let context  = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.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()
            }
        }
    }

但我在NSPersistentContainer上有错误。 错误是:

  

无法推断出'persistentContainer'

的类型      

使用未声明的类型' NSPersistenContainer'

我认为这个问题是因为代码是针对Swift 3.0的,但我使用的是Swift 2.2 我该如何修理它?

2 个答案:

答案 0 :(得分:2)

在iOS 10中添加了

NSPersistentContainer。您正在使用Xcode 7.2.1,这意味着您的Base SDK是iOS 9.因此NSPersistentContainer是一个未知的类。

使用iOS 10和NSPersistentContainer之前存在的核心数据的旧示例。

或更新到Xcode 8.3和iOS 10(你真的应该这样做)。但是,如果您的部署目标是iOS 9或更早版本,则需要注意,如果您尝试使用NSPersistentContainer,您的应用将无法在这些设备上运行。

答案 1 :(得分:0)

嗯,类型NSPersistenContainer确实没有在任何地方声明。 NSPersistentContainer类型是。因此,无论您何时尝试使用NSPersistenContainer,请使用NSPersistentContainer。