热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何将CoreData添加到现有的Xcode9Swift4iOS11项目中?

如何解决《如何将CoreData添加到现有的Xcode9Swift4iOS11项目中?》经验,为你挑选了2个好方法。

请求更新,因为此问题当然已针对先前版本得到解答,最新的搜索结果日期为12月16日与之前的iOS 9和10项目产生无关的兼容性.

文档当然是说在开始一个新项目时选择使用核心数据复选框,我没有选择,但现在认为需要添加iCloud +核心数据以将我的应用程序带到下一阶段 - >其中类似NSFileCoordinator和需要NSFilePresenter,因为在我的应用程序UI中,用户会看到一些TOPICS,每个都有三个OPTIONS,用户可以选择一个选项.对于每个主题,UI然后显示已选择每个选项的总用户数和每个选项的总计PERCENTAGE.

现在,每个选项的选择数量和总数的百分比当然只是在我的原生应用程序中计算 - >但实际上需要在像云一样的中心计算,或者最有可能在网站上计算...但是网站...引发NSFileCoordinator和NSFilePresenter已经解决的同时读/写问题.

因此,如果iCloud +核心数据系统可以插入现有的泛在容器数值总计的基本算术计算 - 在接收来自各个用户的写入数值命令时在云中 - 在发送新的无处不在容器数值总和百分比值之前 - 然后我非常感谢在尝试创建和初始化核心数据堆栈时如何修复下面生成的错误.否则猜测我将不得不刮掉Xcode并转到像PhoneGap这样的混合应用程序,如果这是最好的工作.

因此,请参阅核心数据编程指南:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1

并在我现有项目的开头粘贴以下代码,生成

使用未解析的标识符'persistentContainer'...'managedObjectContext'

......错误.和线

init(completionClosure: @escaping () -> ()) { 

...生成

初始化程序只能在类型中声明

import UIKit

import CoreData
class DataController: NSObject {
  var managedObjectContext: NSManagedObjectContext
  init(completionClosure: @escaping () -> ()) {
    persistentCOntainer= NSPersistentContainer(name: "DataModel")
    persistentContainer.loadPersistentStores() { (description, error) in
      if let error = error {
        fatalError("Failed to load Core Data stack: \(error)")
      }
      completionClosure()
    }
  }
}

init(completionClosure: @escaping () -> ()) {
  //This resource is the same name as your xcdatamodeld contained in your project
  guard let modelURL = Bundle.main.url(forResource: "DataModel", withExtension:"momd") else {
    fatalError("Error loading model from bundle")
  }
  // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
  guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
    fatalError("Error initializing mom from: \(modelURL)")
  }

  let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

  managedObjectCOntext= NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
  managedObjectContext.persistentStoreCoordinator = psc

  let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
  queue.async {
    guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
      fatalError("Unable to resolve document directory")
    }
    let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
    do {
      try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
      //The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
      DispatchQueue.main.sync(execute: completionClosure)
    } catch {
      fatalError("Error migrating store: \(error)")
    }
  }
}

// followed by my existing working code:

class ViewController: UIViewController {

Jay N... 39

转到文件>新文件...iOS下选择核心数据并选择数据模型, 您仍然需要一些代码,无论何时在项目创建期间选择核心数据,xcode都会自动生成.为了得到它,只需创建一个核心数据选项选中的新项目,并复制所有在**// Mark下编写的代码: - AppDelegate.swift中的核心数据堆栈**注释 并添加

import CoreData

以上

可选的

并且不要忘记在刚刚复制的代码的managedObjectModel函数中复制后更改应用程序的名称



1> Jay N...:

转到文件>新文件...iOS下选择核心数据并选择数据模型, 您仍然需要一些代码,无论何时在项目创建期间选择核心数据,xcode都会自动生成.为了得到它,只需创建一个核心数据选项选中的新项目,并复制所有在**// Mark下编写的代码: - AppDelegate.swift中的核心数据堆栈**注释 并添加

import CoreData

以上

可选的

并且不要忘记在刚刚复制的代码的managedObjectModel函数中复制后更改应用程序的名称


***更改应用程序的名称***表示`managedObjectModel`(或现在的`persistentContainer`代码)中的模型名称.例如:`persistentCOntainer= NSPersistentContainer(name:"DataModel")`,其中`DataModel`应该替换为您的应用程序的名称,因为这是Core Data创建的商店的默认名称.(注意:用破折号替换名称中的任何空格,因为在名为"我的应用程序"的应用程序中将有一个名为"My-App"的默认商店)
对于稍后出现的人,您可能还想在AppDelegate.swift的applicationWillTerminate()和applicationDidEnterBackground()方法中添加`self.saveContext()`.

2> iOSDevSF..:

如果您像我一样懒惰,那么这里是您需要从新的Core Data项目中复制的所有代码...(为什么要让每个人都创建一个新项目?)。变更YOUR_APP_NAME_HERE

import CoreData


// MARK: - Core Data stack

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()
    }

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


推荐阅读
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 如何用UE4制作2D游戏文档——计算篇
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了如何用UE4制作2D游戏文档——计算篇相关的知识,希望对你有一定的参考价值。 ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 解决Cydia数据库错误:could not open file /var/lib/dpkg/status 的方法
    本文介绍了解决iOS系统中Cydia数据库错误的方法。通过使用苹果电脑上的Impactor工具和NewTerm软件,以及ifunbox工具和终端命令,可以解决该问题。具体步骤包括下载所需工具、连接手机到电脑、安装NewTerm、下载ifunbox并注册Dropbox账号、下载并解压lib.zip文件、将lib文件夹拖入Books文件夹中,并将lib文件夹拷贝到/var/目录下。以上方法适用于已经越狱且出现Cydia数据库错误的iPhone手机。 ... [详细]
  • 本文介绍了在Linux下安装Perl的步骤,并提供了一个简单的Perl程序示例。同时,还展示了运行该程序的结果。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 有没有一种方法可以在不继承UIAlertController的子类或不涉及UIAlertActions的情况下 ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
author-avatar
天秤蜗牛666
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有