简体   繁体   English

在Swift中仅初始化一次CoreData实体

[英]Initialize CoreData entity only once in Swift

I'm quite new to using CoreData in Swift and I wanted to create a persistent grade manager for learning purposes. 我对在Swift中使用CoreData很陌生,我想创建一个用于学习目的的持久性成绩管理器。

My class structure is as follows: I have a 'Student' entity in my CoreData with a to-many relationship with a 'Course' entity (with a to-many relationship with a 'Grade' entity). 我的类结构如下:我的CoreData中有一个“学生”实体,该实体与“课程”实体具有一对多关系(与“成绩”实体具有一对多关系)。

I want to initialize a student at first startup automatically, so the user only has to add courses and grades, but I can't find out how to do so. 我想在初次启动时自动对学生进行初始化,因此用户仅需添加课程和成绩,但我不知道如何添加。

I currently have the initializer in my viewDidLoad() but that basically means it gets created a lot of times. 目前,我的viewDidLoad()包含初始化程序,但这基本上意味着它已经创建了很多次。

What's the solution to my problem? 我的问题有什么解决方案?

If i am understanding it correctly, you want only 1 entity of student. 如果我正确理解它,则只需要1个学生实体。 Also putting initialiser code in viewDidLoad wont be called multiple times in a single run of the application. 同样,将初始化代码放入viewDidLoad不会在应用程序的单次运行中多次调用。

Sure every time you launch the application, a new student will be created. 当然,每次您启动该应用程序时,都会创建一个新学生。

It has a very basic and easy workaround, which revolves around the concept of fetching and creating. 它有一个非常基本且简单的解决方法,围绕获取和创建的概念展开。

Follow these steps mentioned in the pseudocode : 请执行伪代码中提到的以下步骤:

 methodCreateOfFetchStudent(){
         1. Search Core data for any student entity.
         2. if found then return that studend (there will be only 1 found)
         3. If No student entity is found (array.count == 0) , then create a student with initialisation code.
         4. return that newly created student entity.
  } 

So for the first time when your application stats, in step 2, no student will be found, and it will create a student and return you the entity. 因此,当您的应用程序统计信息首次出现在步骤2中时,将不会找到任何学生,它将创建一个学生并返回您的实体。 Afterwards in each run, the method will return the old created student every time. 之后,在每次运行中,该方法每次都会返回原来创建的学生。

I hope I understood your requirement and this helped you. 希望我了解您的要求,这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM