gpt4 book ai didi

swift - 启用核心数据 Xcode Swift

转载 作者:行者123 更新时间:2023-11-28 15:33:01 25 4
gpt4 key购买 nike

我正在尝试在我的项目中启用核心数据。因为我已经顺利完成了我的项目,所以我错过了在开始时启用核心数据的选项。谁能帮我启用它?谢谢

最佳答案

您可以直接在正在运行的项目中添加核心数据转到您的项目名称右键单击选择新文件并从核心数据部分选择数据模型,您必须在 AppDelegate.swift 文件中配置一些核心数据....

在 AppDelegate 文件中添加这段代码......

import CoreData

// MARK: - Core Data stack

lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.purpleapps.PixBoxNew.PixBox" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "<<YourCoredatanamehere>>", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
print(url)
var failureReason = "There was an error creating or loading the application's saved data."
do {
let myOptions = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: myOptions)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}

return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
//UNDO
// var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

lazy var writerManagedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
// let coordinator = self.persistentStoreCoordinator
var writerManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
// writerManagedObjectContext.persistentStoreCoordinator = coordinator

// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_mocDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil];

NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.mocDidChangeNotification), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)
return writerManagedObjectContext
}()
// MARK: - Core Data Saving support

func mocDidChangeNotification(_ notification : Notification){
DispatchQueue.main.async {
self.managedObjectContext.mergeChanges(fromContextDidSave: notification)
}
}

func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.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()
}
}
}

关于swift - 启用核心数据 Xcode Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44580817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com