无法在 swift 文件中创建上下文
Posted
技术标签:
【中文标题】无法在 swift 文件中创建上下文【英文标题】:unable to create a context in swift file 【发布时间】: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
真的不知道我在这里做错了什么。
【问题讨论】:
错误是什么? 【参考方案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
【讨论】:
以上是关于无法在 swift 文件中创建上下文的主要内容,如果未能解决你的问题,请参考以下文章
无法在 Visual Studio 2017 的共享项目中创建文件夹
多上下文麻烦。无法在 Core Data 中创建两个队列(主队列和私有队列)保存数据
在 SDL 1.3 中创建 OpenGL 3.2/3.x 上下文