“NSPercientContainer”仅在 iOS 10.0 或更高版本上可用

2024-03-22

我是 iOS 应用程序开发新手。我开发了一个应用程序,在用户登录时显示一个网站。它适用于设置为 10.1 的部署目标。为了使其与 IOS 8 兼容,我尝试将部署目标设置为 8,因为我遇到了以下错误。

'NSPersistentContainer' is only available on iOS 10.0 or newer

任何人都可以帮助我修改代码以使其与 IOS 8,9 和 10 兼容。 代码:8.2.1 斯威夫特版本:3.2

import UIKit
import CoreData

 @UIApplicationMain

 class AppDelegate: UIResponder, UIApplicationDelegate {

     var window: UIWindow?


    func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

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

    }

经过几天的搜索,我得到了解决方案...... 只需替换为 appdelegate.swift 文件中的以下内容...它有效..

  // MARK: - Core Data stack

@available(iOS 10.0, *)
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: "coreDataTestForPreOS")
    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
}()

// iOS 9 and below
lazy var applicationDocumentsDirectory: URL = {

    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: "coreDataTestForPreOS", 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")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
    } 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
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {

    if #available(iOS 10.0, *) {

        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)")
            }
       }
    } else {
        // iOS 9.0 and below - however you were previously handling it
            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()
                }
            }

        }
    }


}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“NSPercientContainer”仅在 iOS 10.0 或更高版本上可用 的相关文章

  • Swift 将十进制坐标转换为度、分、秒、方向

    我怎样才能将其转换为快速 我最好的猜测是所有 int 都变成了 var 删除所有导致 的 此外 如果有的话可以给我指出一个很好的来源来了解事物如何转换 那就太好了 NSString coordinateString int latSecon
  • 如何检测文本是否可读?

    我想知道是否有一种方法可以告诉给定的文本是人类可读的 我所说的人类可读的意思是 它有一些含义 格式就像某人写的文章 或者至少是由软件翻译器生成的供人类阅读的文章 这是背景故事 最近我正在制作一个应用程序 允许用户将短文本上传到数据库 在部署
  • 如何在 swift 3 中的表视图单元格中实现集合视图的分页?

    在这里 我有一个布局 其中我的表视图单元格之一由集合视图组成 在这个布局中我需要实现分页 但我无法使用func collectionView collectionView UICollectionView willDisplay cell
  • Swift 为 .toInt 提供Optional(3) 而不是 3

    尝试从字段中提取数字并继续获取可选 数字 而不是数字 IBOutlet weak var years UITextField IBAction func calculateYear sender AnyObject var a years
  • SwiftUI TabbedView 仅显示第一个选项卡的内容

    我正在尝试建立一个TabbedView使用以下简单代码 TabbedView Text Hello world tabItemLabel Text Hello Text Foo bar tabItemLabel Text Foo 运行时 两
  • UI键盘回避和自动布局

    鉴于 iOS 6 中对自动布局的关注以及 Apple 工程师的推荐 查看 WWDC 2012 视频 我们不再直接操作视图的框架 那么如何仅使用自动布局和 NSLayoutConstraint 来避免键盘呢 Update 这看起来是一个合理的
  • Swift 生成器上的链式表达式错误

    迅速回复 zip 1 2 3 7 8 9 generate next repl swift 1 22 error value of type Zip2Generator
  • React Native 检查平板电脑或屏幕是否以英寸为单位

    我为平板电脑和移动设备建立了不同的渲染逻辑 我想知道是否有办法获取屏幕尺寸 以英寸为单位 或者甚至可能是任何模块自动检测设备是否是平板电脑 我没有直接使用尺寸 API 来获取屏幕分辨率的原因是 许多 Android 平板电脑的分辨率低于许多
  • 如何在iOS应用程序中实现互斥锁[重复]

    这个问题在这里已经有答案了 可能的重复 GCD 如何从两个线程写入和读取变量 https stackoverflow com questions 11070947 gcd how to write and read to variable
  • 块执行后变量返回 null

    我正在调度一个队列来在单独的线程上下载一些 flickr 照片 在 viewWillAppear 中 当我记录块内数组的内容时 它完美地显示了所有内容 dispatch queue t photoDowonload dispatch que
  • 为什么我的matchedGeometryEffect根据右下点移动?

    我只是尝试使用matchedGeometryEffect 制作一些动画 但是 存在一个错误 即该对象是根据右下点而不是中心进行动画处理的 我使用的代码在这里 import SwiftUI struct Test View Namespace
  • 将深层链接传递到 iOS 模拟器?

    我想找到一种更简单的方法来在 iOS 模拟器中调用深层链接 在 Android 上 您可以使用 ADB 通过控制台将链接传输到模拟器中 是否有类似的方法或解决方法来打开最新 iOS 模拟器的深层链接 您可以在终端中输入以下内容 xcrun
  • 如何将计算值转换为文字以进行枚举初始化

    我遇到了枚举的问题 因为我想将 case 初始化为双精度值PI 180 有没有办法通过常量或一些时髦的魔法获取这个计算值并将其转换为文字 以便我可以初始化枚举 我宁愿不必做3 14 我宁愿使用该值的实际编译器和硬件计算表示 所以我的第一次尝
  • 当前位置在 Google 地图中不起作用

    我在 swift 3 中集成了谷歌地图 当地图屏幕出现而不显示当前位置时 我在 plist 文件中添加了两个键 并设置了 CLLocationManager delegate 和 requestAlwaysAuthorization cla
  • 如何在 iOS 中通过 3G 连接创建无线热点

    如果我愿意 我将如何创建一个像这样的应用程序MyWi http intelliborn com mywi html 即 WiFi 网络共享应用程序 实现该功能需要哪些步骤 我需要使用哪些框架 库 我们的目标不是尝试将此应用程序放入应用程序商
  • 编辑模板身份验证 Firebase

    您好 我使用 Firebase 启动了一个新应用程序 然后执行身份验证方法 但我需要编辑电子邮件地址验证和更改电子邮件地址的模板 这两个选项无法编辑 但重置密码后可以编辑模板 字段 消息 该消息仅在选项 电子邮件地址验证和更改电子邮件地址
  • EXC_BAD_INSTRUCTION 的 CoreData 错误(代码=EXC_I386_INVOP,子代码=0x0)

    当我打开并发调试开关 com apple CoreData ConcurrencyDebug 1 来跟踪 CoreData 的所有并发问题时 在调用 insertingNewObjectForEntityForName 时不断发生崩溃 Xc
  • 如何解决创建 SwiftData #Predicate 的编译器错误?

    我一直在尝试很多方法来解决这个问题 我正在尝试使用谓词获取 SwiftData 记录 但我尝试的一切都会导致两个错误 初始化程序 init 要求 Item 符合 Encodable 初始化程序 init 要求 Item 符合 Decodab
  • 将对象映射到 TableView 部分的 Swift 二维数组

    我想不出更好的方法来做到这一点 我将学生对象的所有属性映射到二维数组中 所以我的电视有几个部分 我也不能使用静态表视图 如果是这样 这个问题就不会存在 所以我在 TVC 中的代码 let currentUser PFUser current
  • Phonegap - cordova 在 Android 和 iOS 设备上延迟且缓慢

    我刚刚开始使用 zend studio 开始我的第一个 PhoneGap 项目 但是 在我构建并部署它之后 该应用程序非常慢 Android 和 iOS 均可 滚动滞后 如果我按下按钮 转到下一页的速度很慢 有什么办法可以提高它的性能吗 提

随机推荐

  • 了解 matplotlib:plt、figure、ax(arr)?

    我并不是很陌生matplotlib我非常羞愧地承认我一直使用它作为尽可能快速 轻松地获得解决方案的工具 所以我知道如何获得基本的情节 子情节和东西 并且有相当多的代码可以不时地重用 但我没有 深入的 呃 知识 matplotlib 最近我想
  • R 中的 Reduce() 对相似变量名导致错误

    我有 19 个由 lapply 和 split 操作生成的嵌套列表 这些列表的形式如下 list1 Var col1 col2 col3 A 2 3 4 B 3 4 5 list2 Var col1 col2 col3 A 5 6 7 B
  • MYSQL 选择一列中的两个值

    我需要从 mysql 表中选择一行 该表中有两行具有相同的值 TABLE articleId keywordId 现在我需要选择一篇文章 其关键字 Id 1 以及关键字 Id 12 每个关键字的链接都有自己的记录 如何执行一个选择查询来知道
  • tomcat 7.0.42 上的 403 访问被拒绝

    我有错误tomcat 7 0 42 上的 403 访问被拒绝访问 Tomcat Manager 应用程序时 这就是我所拥有的tomcat 用户 xml文件 我曾多次尝试更换角色 但没有成功 注意 我从 NetBeans 7 3 1 启动 停
  • 获取 icloud Web 服务端点以获取数据

    我的问题可能看起来很愚蠢 但我在谷歌上进行了太多搜索后才问这个问题 但没有任何线索 我正在使用 iCloud 网络服务 为此 我已将此 Python 代码转换为 PHP https github com picklepete pyiclou
  • ASP.NET Identity 的 IUserSecurityStampStore 接口是什么?

    查看 ASP NET Identity ASP NET 中的新成员身份实现 我在实现自己的接口时遇到了这个接口UserStore Microsoft AspNet Identity Core dll namespace Microsoft
  • 检查 bash 中的索引数组是稀疏还是密集

    我在 bash 中有一个动态生成的索引数组 想知道它是否是sparse or dense 如果在最后一个条目之前有未设置的索引 则数组是稀疏的 否则数组是密集的 该检查应该在每种情况下都有效 即使是空数组 非常大的数组 扩展时超过 ARG
  • 如何聚焦未停靠的 Chrome 调试窗口的相应选项卡?

    在开发时 我经常在 Chrome 浏览器中打开很多选项卡 我总是在单独的窗口中使用未固定的 Chrome DevTools 假设我已经打开给定选项卡的 DevTools 然后在另一个选项卡中对 SO 进行了一些搜索 那么 如果我再次聚焦 C
  • 我可以解析外部网页的目录列表吗?

    是否可以解析外部网页的目录列表 因为该网页是可访问的 并且当我访问它时它会显示文件列表 我只想知道是否可以在 PHP 中动态解析文件以及如何解析 谢谢 抱歉不清楚 我的意思是目录列表 例如 http www ibiblio org pub
  • JComboBox 弹出菜单不出现

    我在 JPanel 中有一个 JComboBox 它本身嵌套在其他几个 JPanel 中 它填充了枚举的成员 我遇到了一个问题 当我单击展开按钮时 弹出菜单不会出现 以下是我迄今为止收集到的信息 1 第一次点击展开按钮没有任何反应 第二次单
  • LINQ 基于 IList 从 IList 中删除某些元素 [重复]

    这个问题在这里已经有答案了 如何使用 LINQ 从一个基于另一个 IList 的 IList 中删除某些元素 我需要从 list1 中删除 ID 出现在 list2 中的记录 下面是代码示例 class DTO Prop int ID Pr
  • 如何在 Windows 10 Universal 中获取设备的唯一标识符?

    这是我为 Windows Universal 8 1 获取唯一 DeviceID 的旧实现 但 HardwareIdentification 类型不再存在 private static string GetId var token Hard
  • 如何在android应用程序中从twitter获取用户信息?

    我正在将 Twitter 集成到我的 Android 应用程序中 我可以为用户授权该应用程序 现在 我正在寻找一个 API 它可以为我提供登录用户的信息 如名字 姓氏 电子邮件等 我已经为 Facebook 做了这个 facebook re
  • Java中如何查找未关闭的I/O资源?

    Java 中的许多 I O 资源 例如 InputStream 和 OutputStream 在使用完毕后需要关闭 如前所述here http www coderanch com t 202922 Performance java Uncl
  • Matlab中如何imwarp转点?

    我正在使用 Matlab 将图像转换为目标图像 我有几何变换 tform 例如这是我的 tform 1 0235 0 0022 0 0607 0 0 0276 1 0002 0 0089 0 0 0170 0 0141 1 1685 0 1
  • 如何将 openssl-sys 箱静态链接到共享库?

    我正在使用一个依赖于的库openssl 系统 https github com sfackler rust openssl 根据文档 如果我指定OPENSSL STATIC 1作为环境变量 OpenSSL 将静态链接到共享库输出中 Due
  • WinForms 多线程:仅当前一个更新完成时才执行 GUI 更新

    我有带有一些后台处理的多线程应用程序 它有长时间运行的 UI 更新 在 UI 线程本身上 它们是通过众所周知的从后台线程调用的MSDN 上的资源 http msdn microsoft com en us library 757y83z4
  • 用颜色填充图像但保留 Alpha(PIL 中的颜色叠加)

    基本上 我正在尝试创建一个函数来获取给定的图像和颜色 对于图像中的每个像素 它将保留原始 alpha 值 但会将颜色更改为给定的颜色 例如 如果函数获取下面的箭头图像和红色 它将输出以下图像 在 Photoshop 和其他图像编辑器中 这种
  • 从函数创建矩阵

    我想从函数创建一个矩阵 这样 3 3 如果行索引小于给定阈值 k 则矩阵 C 的值等于 1 import numpy as np k 3 C np fromfunction lambda i j 1 if i lt k else 0 3 3
  • “NSPercientContainer”仅在 iOS 10.0 或更高版本上可用

    我是 iOS 应用程序开发新手 我开发了一个应用程序 在用户登录时显示一个网站 它适用于设置为 10 1 的部署目标 为了使其与 IOS 8 兼容 我尝试将部署目标设置为 8 因为我遇到了以下错误 NSPersistentContainer