当前位置:网站首页>Coredata data persistence
Coredata data persistence
2022-06-25 16:17:00 【super_ man_ Breezy】
CoreData Introduce
CoreData Is a powerful data persistence technology , be located SQLite Above the database , It avoids the SQL Complexity , It allows us to interact with the database in a more natural way .CoreData Provide data –OC Object mapping relationship to achieve data and object management , This does not require any SQL Statements can manipulate them . CoreData The data persistence framework is Cocoa API Part of ,⾸ Next in iOS5 Version of the system , It allows for Entity - attribute - Value model Organization data , And XML、⼆ Base file perhaps SQLite data ⽂ Pieces of The format of persistent data
CoreData And SQLite Contrast
SQLite
1、 be based on C Interface , Need to use SQL sentence , Code cumbersome
2、 When dealing with large amounts of data , Table relationships are more intuitive
3、 stay OC Is not visualization , Not easy to understand
CoreData
1、 visualization , And undo/redo Ability
2、 Can achieve a variety of file formats :
* NSSQLiteStoreType
* NSBinaryStoreType
* NSInMemoryStoreType
* NSXMLStoreTyp
3、 Apple official API Support , And iOS It's closer together
CoreData Core classes and structures
NSManagedObjectContext( Data context )
- Object management context , Responsible for the actual operation of data ( important )
- effect : insert data , Query data , Delete data , Update data
NSPersistentStoreCoordinator( Persistent storage assistant )
- Equivalent to a database connector
- effect : Set the name of the data store , Location , storage , And storage time
NSManagedObjectModel( Data model )
- All tables or data structures in the database , Contains the definition information of each entity
- effect : Add the properties of the entity , Building relationships between attributes
- Operation method : View editor , Or code
NSManagedObject( Managed data records )
- Table records in the database
NSEntityDescription( Physical structure )
- Equivalent to table structure
NSFetchRequest( Data request )
- Equivalent to a query statement
The suffix is .xcdatamodeld My bag
- Inside is .xcdatamodel file , Edit with the data model editor
- Compiled as .momd or .mom file
Diagram of the relationship between various types

CoreData database Manually create
The steps are as follows
1. Create model file [ It's like a database ]
2. Add entities [ A watch ]
3. Create entity class [ Equivalent model -- Table structure ]
4. Generate context Generate database by associating model files
0、 Create a project
1、 Manually create CoreData Data time , We create a project as usual , There is no need to check Use Core Data: 
1、 Create model file
1、 Go to create new file ,command+N Or as shown in the figure below

2、 Select the model file type , Here's the picture :

3、 Set file name , Here's the picture :

4、 Model file created successfully , Will appear later

2、 Create entities
1、 Create entities in a visual way , The functions of entities are similar to our Model class , The specific operations are as follows: :

3、 Create entity class
Create entities with visualization , But we want to get the corresponding data and name , You must associate classes , So create an entity class , The steps are as follows :
1、 Go to create new file

2、 Select file type , Entity class file type selection :NSManagedObject subclass

3、 Select the model file

4、 Select entities

5、 Create success

After the entity file is created successfully, the system automatically generates the corresponding Classes and properties , Class name Corresponding The entity name , attribute Corresponds to The attribute name ; If our attribute is a basic data type , Then the default will help us convert to NSNumber Properties of type .
* The old version : Only one pair of files are generated , That is, classes and attributes are all together
* The new version : Generate a pair of class files , Regenerate into a pair of categories , Generate attributes in the class
4、 Generate context Associated database
Before creating the context and the associated database, let's take a look at the relational dependency graph :

From the picture above we can see , To generate context , Need to have Database assistant and Model Support for ; It's like SQLite In the same , Want to operate the database , You have to have database , And create surface ; Let's look at the implementation code :
<code class="hljs objectivec has-numbering">- (<span class="hljs-keyword">void</span>)viewDidLoad {
[<span class="hljs-keyword">super</span> viewDidLoad];
<span class="hljs-comment">//1、 Create model objects </span>
<span class="hljs-comment">// Get model path </span>
<span class="hljs-built_in">NSURL</span> *modelURL = [[<span class="hljs-built_in">NSBundle</span> mainBundle] URLForResource:@<span class="hljs-string">"School"</span> withExtension:@<span class="hljs-string">"momd"</span>];
<span class="hljs-comment">// Create model objects from model files </span>
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
<span class="hljs-comment">//2、 Create a persistence assistant </span>
<span class="hljs-comment">// Using model objects to create helper objects </span>
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
<span class="hljs-comment">// The name and path of the database </span>
<span class="hljs-built_in">NSString</span> *docStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, <span class="hljs-literal">YES</span>) lastObject];
<span class="hljs-built_in">NSString</span> *sqlPath = [docStr stringByAppendingPathComponent:@<span class="hljs-string">"mySqlite.sqlite"</span>];
<span class="hljs-built_in">NSLog</span>(@<span class="hljs-string">"path = %@"</span>, sqlPath);
<span class="hljs-built_in">NSURL</span> *sqlUrl = [<span class="hljs-built_in">NSURL</span> fileURLWithPath:sqlPath];
<span class="hljs-comment">// Set up database related information </span>
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:<span class="hljs-literal">nil</span> URL:sqlUrl options:<span class="hljs-literal">nil</span> error:<span class="hljs-literal">nil</span>];
<span class="hljs-comment">//3、 Create context </span>
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
<span class="hljs-comment">// Association persistence assistant </span>
[context setPersistentStoreCoordinator:store];
_context = context;
}
</code><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li></ul><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li></ul>- After this , Our whole CoreData Even if the database is created , The whole process is manual , So for
principleCan better understand ; - After running, the database has been created , Enter the corresponding path , We can see the created database file ;
- Use the tool to open , It is found that the corresponding table has also been created for us ;
- After the above steps are completed , In the follow-up work, we do not need to do any work related to the database , All the work dealing with the database is left to CoreData To achieve .
CoreData database System creation
Using the built-in method to create a database is the same as the manual method , Only the system will create the model file 、 Generate context 、 The work of associated database helps us do , We don't have to do any more of this ;
Saying so much , Let's take a look at how to use the system self creation CoreData database
For those created by the system itself , There are only two steps :
- Create a project
- The created entity is already associated with the entity class
Create a project
1、 Manually create CoreData Database time , We create a project as usual , Particular attention : Be sure to check Use Core Data:

2、 After the project is created , The system will automatically help us create a project with the same name Model file ; And help us write Generate context and Associated database Code for :


After the above is done , We just need to create entities , And associated entity classes
Create entities Associated entity class
Create entities and associated entity classes and Create the database manually The way is the same , Refer to manual creation 2、3 that will do
Jane books links :http://www.jianshu.com/p/880dd63c5f5e
边栏推荐
- 转换Cifar10数据集
- Tensorflow loading cifar10 dataset
- [Third Party framework] retrofit2 (2) - add point configuration of network access framework
- [problem solving] dialogfragment can not be attached to a container view
- What is the NFT digital collection?
- This article will help you understand the common concepts, advantages and disadvantages of JWT
- Uncover gaussdb (for redis): comprehensive comparison of CODIS
- Why does golang's modification of slice data affect the data of other slices?
- Servlet details
- Based on neural tag search, the multilingual abstracts of zero samples of Chinese Academy of Sciences and Microsoft Asiatic research were selected into ACL 2022
猜你喜欢

商城风格也可以很多变,DIY 了解一下!

Popular cross domain

10款超牛Vim插件,爱不释手了
Why does golang's modification of slice data affect the data of other slices?

How to reload the win10 app store?
Mixed density network (MDN) for multiple regression explanation and code example

一行代码可以做什么?

Don't underestimate the integral mall, its role can be great!

Share the code technology points and software usage of socket multi client communication
Create raspberry PI image file of raspberry pie
随机推荐
Report on Hezhou air32f103cbt6 development board
GridLayout evenly allocate space
读配置、讲原理、看面试真题,我只能帮你到这了。。。
GO语言-什么是临界资源安全问题?
Go language - what is critical resource security?
Prototype chain analysis
Error: homebrew core is a shallow clone
Advanced SQL statement 1 of Linux MySQL database
Introduction to database transactions
Servlet详解
Helsinki traffic safety improvement project deploys velodyne lidar Intelligent Infrastructure Solution
B站付费视频使up主掉粉过万
说下你对方法区演变过程和内部结构的理解
The release of autok3s v0.5.0 continues to be simple and friendly
GO语言-锁操作
What is OA
10 Super VIM plug-ins, I can't put them down
Tensorflow loading cifar10 dataset
What are the reasons why the game industry needs high defense servers?
error Parsing error: Unexpected reserved word ‘await‘.