gpt4 book ai didi

ios - 如何做我的 appDelegate coredata 支持 ios 9 我正在使用 xCode 8

转载 作者:行者123 更新时间:2023-12-01 19:34:48 29 4
gpt4 key购买 nike

我实际上遇到了一个问题,我使用的是 Xcode 8、iOS 10,但在我的运行目标中我给了它 9.1,问题发生时我包含了 CoreData,但我需要正常工作 enter image description here iOS 9 和 iOS 10

我把图片放在这里

enter image description here

这部分代码

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

And in this part are my functions

func saveData(){

let appDelegate = UIApplication.shared.delegate as! AppDelegate
if #available(iOS 10.0, *) {
let context = appDelegate.persistentContainer.viewContext
let newToken = NSEntityDescription.insertNewObject(forEntityName: "Token_entity", into: context)
newToken.setValue("85724985724897247ifeifjhadjkfhsauq89r8479138941874193874", forKey: "accessToken" )
do
{

try context.save()
print("SAVED")

}
catch
{

///PROCESS ERROR

}

} else {
// Fallback on earlier versions
}
}


func requestCoreData (){

let appDel = UIApplication.shared.delegate as! AppDelegate
if #available(iOS 10.0, *) {
let contex = appDel.persistentContainer.viewContext
let requests = NSFetchRequest<NSFetchRequestResult>(entityName: "Token_entity")
requests.returnsObjectsAsFaults = false


do
{

let results = try contex.fetch(requests)
if results.count > 0
{

for result in results as! [NSManagedObject]{

if let tokenrequest = result.value(forKey: "accessToken") as? String
{

print(tokenrequest)


}



}


}

}
catch
{

///PROCESS ERROR

}


} else {
// Fallback on earlier versions
}

}

最佳答案

当您创建选择该选项的项目时,iOS 9 和早期版本的 Core Data 代码默认进入应用程序委托(delegate),其主要区别在于应用程序访问 ManagedObjectContext 的方式。在 iOS 10 中,上下文是通过一个名为 NSPercientContainer 的新单例对象访问的(请参阅下面使用 Core Data 创建的 iOS 10 项目中的应用程序委托(delegate)中的代码)。如果您的目标是 < iOS 10,则需要删除对持久容器的所有引用。以下是您需要删除的应用程序委托(delegate)内的 iOS 10 变量 perpetualContainer:

class AppDelegate: UIResponder, UIApplicationDelegate {

...

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "CustomNumericKeypad")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {

fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
}

以下是检索 iOS 9 上下文所需的代码:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator =
{
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")

do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
let dict : [String : Any] = [NSLocalizedDescriptionKey : "Failed to initialize the application's saved data" as NSString,
NSLocalizedFailureReasonErrorKey : "There was an error creating or loading the application's saved data." as NSString,
NSUnderlyingErrorKey : error as NSError]
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}

return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

您需要更改的唯一一件事是调用应用程序委托(delegate)中的 saveContext() 方法时引用上下文的方式:

iOS 10 func saveContext () {
让 context = persistentContainer.viewContext
...

iOS 9 func saveContext () {
让上下文=托管对象上下文
...

有一种比较简单的方法来实现两种获取上下文的方法,以便您的代码与操作系统无关,以防您在操作系统 9 之间来回切换目标时不想担心它开发期间有 10 个。看这个blog post有关如何执行此操作的说明/示例代码。

关于ios - 如何做我的 appDelegate coredata 支持 ios 9 我正在使用 xCode 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41051952/

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