【问题标题】:unable to create a context in swift file无法在 swift 文件中创建上下文
【发布时间】:2019-02-04 09:19:11
【问题描述】:

我需要从 CoreData 获取一些数据并且需要经常这样做,因此尝试为它创建实用程序类。 当我尝试为它创建上下文时,它给了我错误,下面是代码。 我添加了一个新的 .swift 文件并粘贴在下面的代码

import Foundation
import UIKit
import CoreData

class armyDataSource{

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext


}

真的不知道我在这里做错了什么。

【问题讨论】:

  • 错误是什么?

标签: ios swift core-data


【解决方案1】:

如果你想为核心数据管理器创建一个包装类,你可以在你的实现的 swift 文件中编写如下代码所示的类。

 import UIKit
 import CoreData
class CoreDataManager {


static let sharedManager = CoreDataManager()
private init() {} // Prevent clients from creating another instance.

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

【讨论】:

    【解决方案2】:

    您不能像在类中那样初始化这些属性。您需要在方法中进行此初始化,最好在 init 调用中进行。

    不能在属性初始化器中使用实例成员“appDelegate”;属性初始化程序在“self”可用之前运行

    所以这意味着你不能使用一个属性来初始化另一个属性,因为这一切都是在调用 init 之前完成的,并且 self 完全可用。

    试试这个:

    class armyDataSource {
    
        let appDelegate: UIApplicationDelegate
        let context: NSManagedObjectContext
    
        init() {
            appDelegate = UIApplication.shared.delegate as! AppDelegate
            context = appDelegate.persistentContainer.viewContext
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2016-03-17
      • 2021-12-23
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多