我需要从CoreData中获取一些数据,并且需要经常执行,因此尝试为其创建实用程序类。 当我尝试为其创建上下文时,它给了我错误,下面是代码。 我添加了一个新的.swift文件并粘贴在代码下方
import Foundation
import UIKit
import CoreData
class armyDataSource{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
}
真的不确定我在这里做什么错。
答案 0 :(得分:0)
您不能像在类中那样初始化这些属性。您需要在方法中进行此初始化,最好在init调用中进行。
不能在属性初始化程序中使用实例成员'appDelegate';属性初始化程序在“自我”可用之前运行
因此,这意味着您不能使用属性来初始化另一个属性,因为这都是在调用init和self完全可用之前完成的。
尝试以下方法:
class armyDataSource {
let appDelegate: UIApplicationDelegate
let context: NSManagedObjectContext
init() {
appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
}
答案 1 :(得分:0)
如果要为核心数据管理器创建包装类,则可以在实现时将文件如下所示的类写到一个快速文件中。
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)")
}
}
}
}