我需要获取从CoreData一些数据,并需要做的是频繁,因此试图创建的实用工具类的。当我尝试为它创建上下文,它给我的错误及以下的代码。我添加了一个新的.swift文件,下面的代码粘贴
import Foundation
import UIKit
import CoreData
class armyDataSource{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
}
真的不知道自己做错了什么,我在这里做了。
如果你想创建核心数据管理的包装类像您实现迅速的文件中给出下面的代码,你可以写的类。
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)")
}
}
}
}
你不能在类初始化这些属性这样。你需要做的这个初始化的方法,最好在init调用。
属性初始化中不能使用实例成员“的appDelegate”;属性初始化之前的“自我”运行可用
因此,这意味着你不能用一个属性来初始化另一个属性,因为这是所有做初始化被称为自我完全可用之前。
试试这个:
class armyDataSource {
let appDelegate: UIApplicationDelegate
let context: NSManagedObjectContext
init() {
appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
}