Meet coredata – get to know coredata

This article belongs to the original of “Jianshu Liu Xiaozhuang”. Please indicate:

< Jianshu Liu Xiaozhuang >

`During this period, the company has been relatively busy, and together with the small partners in the group, the company’s project has been rewritten according to the previous logic. Because the project is relatively large, and the iteration of the previous project and other projects should be considered, so far only the first phase has been written.
In the previous project, SQLite was mainly used as the local persistence solution. This rewrite project intends to change the persistence solution. So we discussed and chose Apple’s “Pro son” coredata.
In the process of using coredata, I also learn and practice at the same time. In the process of learning, some high-quality blogs have also helped me a lot, such as and other blogs, which are not listed here. Thank you very much. `

`In fact, many people don’t know coredata. But after my study, coredata is still very good. So just like the title of this series – meet coredata, and plan to write this series to meet coredata.
This series of blogs will be from simple to complex. In addition to basic use, coredata will also include multithreading, batch data processing and other contents, many of which are touched by our company in the process of project development. We also envisage some extreme situations, and the solutions will be reflected in this series of blogs. `

`I have not been in contact with coredata for a long time, only spent a period of time learning coredata.
This series of articles focuses on the use of coredata through graphical interface, not all of which are pure code. In addition, it’s really troublesome to operate that way, and on the contrary, it loses the advantages and essence of coredata. `

If there is any omission or mistake in the article, please put forward it in time, thank you! A kind of

Meet coredata - get to know coredata

Written in front

stayCoreDataThere are some commonly used classes in, and the titles may vary. So here are some key words to understand the following content. Many of these conventions appear in Apple’s official documents.
NSPersistentStoreCoordinator(persistent store Coordinator), abbreviated asPSC
NSManagedObjectContext(managed object context), abbreviated asMOC
NSManagedObjectModel(managed object model), abbreviated asMOM
NSManagedObjectAnd its subclasses, according to English translation and its functions, are calledmanaged objects
Suffix named.xcdatamodeldBecause it stores the data structure and representation of all entities, it is calledModel file

What is coredata?

A brief introduction

CoreDataAppear iniOS3Is a data storage framework introduced by apple.CoreDataProvides an object relation mapping(ORM), similar toJavaThe Hibernate framework of.CoreDataCan beOCObjects are stored in the database, or data in the database can be converted toOCObject, no manual writing is required during this processSQLStatement, this is the system to help us complete.

CoreDataThe biggest advantage is that there is no need to write anySQLSentence,CoreDataIt encapsulates the operation process of the database, as well as the data andOCObject. So we are usingCoreDataIn the process, many operations are just like database operations, including filtering conditions, sorting and other operations.

This is equivalent toCoreDataIt’s doneModelLayer, for exampleModelThe representation and persistence of layer can effectively reduce the workload of development and makeModelLayer design is more object-oriented.

Is coredata easy to use?

I’ve heard it before,CoreDataIt’s easier to start, but it’s hard to learn. That’s what a lot of people sayCoreDataOne of the reasons why it’s not easy to use is that there’s something wrong with the way it’s used, or it’s not really masteredCoreData

In terms of performance,CoreDatathanSQLiteIt’s a little bit worse. But for the mobile end,High concurrency of large websites is not required, so this performance difference has almost no impact, so this point can be ignored. In a later article, we will showCoreDataComparison of advantages and disadvantages, as well as detailed performance evaluation.

Several main classes of coredata
  • NSManagedObjectContext

Managed object contextMost of the data operations are related to this class.

  • NSManagedObjectModel

Managed object model, a managed object model is associated with a model file(.xcdatamodeld), which stores the data structure of the database.

  • NSPersistentStoreCoordinator

Persistent storage coordinator, which is responsible for coordinating the relationship between the store and the context.

  • NSManagedObject

Managed object classAllCoreDataAll managed objects in must inherit from the current class and create a managed object class file based on the entity.

Coredata simple creation process
  1. Model file operation

1.1 create model file with suffix.xcdatamodeld。 After creating the model file, you can add entities and other operations inside it (used to represent the data structure of the database file)
1.2 add an entity (representing the table structure in the database file). After adding an entity, you need to create a managed object class file through the entity.
1.3 add attribute and set type. You can set default value and other options in the right panel of attribute. (each data type setting option is different)
1.4 create request template, set configuration template, etc.
1.5 create managed object class file according to specified entity (based onNSManagedObjectClass file of)

  1. Instantiate context object

2.1 create managed object context(NSManagedObjectContext)
2.2 create managed object model(NSManagedObjectModel)
2.3 create persistent storage coordinator according to managed object model(NSPersistentStoreCoordinator)
2.4 associate and create local database files and return persistent storage objects(NSPersistentStore)
2.5 assign the persistent storage coordinator to the managed object context to complete the basic creation.

Coredata structure

The structure of coredata

I saw several introductions beforeCoreDataThe structure of the picture, feel the structure of the expression is relatively clear. We can get to know each other through these picturesCoreData, which will be explained in detail in later articles.

Meet coredata - get to know coredata

Initialization is shown in the figure aboveMOCSome of the classes involved are instantiated by these classes and finally constitute usableMOC。 The number in the figure is an instantiation with data processing capabilityMOCProcedure, which is the same as the instantiation context object described above.

Meet coredata - get to know coredata

stayPSCCreate and associate a local database and set toMOCOfpersistentStoreCoordinatorAfter the attribute,MOCIt has the ability to operate on all managed objects in the current store. But it’s important to note that,MOCFor managed objectsLazy loadingWill be loaded into theMOCIn the cache of.

Meet coredata - get to know coredata

MOMAfter the object loads the model file, get the structure of all the entities in the model file. BecauseMOMThe structure of the model file is stored in,PSCNeed to passMOMObject instantiates the local database.

Meet coredata - get to know coredata

All properties existEntity, as well as the related properties and request templates, which will be discussed in the following chapters.

Meet coredata - get to know coredata

Can passEntityCreate inheritance fromNSManagedObjectClass. This file is the managed object used in development. It has the representation function of model object,CoreDataThis class and its subclasses do the local persistence of.

Persistent storage scheduler

stayCoreDataThere are two parts in the whole structure. One isNSManagedObjectContextThe model part of management, which manages allCoreDataManaged object for. One isSQLiteThe local persistence part of the implementation, responsible for andSQLData exchange is mainly conducted byNSPersistentStoreClass operations. That’s what it’s made ofCoreDataThe general structure of.

Meet coredata - get to know coredata

As can be seen from the figure, the two parts are relatively independent, and the interaction between the two parts is made by a persistent storage scheduler(NSPersistentStoreCoordinator)To control. Upper strataNSManagedObjectContextThe stored data is handed over to the persistent scheduler, and the scheduler calls the specific persistent storage object(NSPersistentStore)To operate the corresponding database file,NSPersistentStoreResponsible for the implementation details of storage. This is a good way to separate the two parts.

Personal caprice

aboutCoreDataBecauseCoreDataThe underlying storage is usedSQLiteRealized, so I usedCoreDataStructure andSQLiteBy contrast, we find that there are many similarities.

.xcdatamodeldThe file represents the file structure of the database.xcdatamodeldCompiled.momdFile generation database. Each entity represents a data table. The relationship between entities isSQLiteThe foreign key.

The following is the picture.CoreDataThe structure of the underlying storage. The part circled in red points to the primary key subscript of the associated table. for example1The primary key subscript pointing to the associated table is1Row.

Meet coredata - get to know coredata

Coredata talks

Coredata data storage security

CoreDataNature or useSQLiteFor storage, no additional encryption function is provided, and specific data encryption and decryption need to be completed by ourselves.

Coredata’s data storage structure on hard disk

Meet coredata - get to know coredata

adoptPSCDesignated creationSQLiteAfter the directory, a database file will be generated under the specified directory, and two files with the same name but different suffixes will also be generated, among which only the suffixes are.sqliteIs the file that stores the data.

Three tables will be generated by default in this database file,Z_METADATAZ_PRIMARYKEYZ_MODELCACHEOther watches of our ownUppercase ZThe first.

In each table, three fields are generated by default,Z_PKZ_ENTZ_OPTAll three fields areUppercase ZBeginning and underlined. Other fields are our own,Uppercase ZStart without underline.

Coredata execution efficiency

Most of the projects on the market now useSQLiteAs a durable solution, andCoreDataThe use of is not very common. For this problem, I think the first thing is that many projects started earlier, at that time manyiOSProgrammers are more familiar with other languagesSQLiteSo useSQLiteMore. If we don’t do large project refactoring later, it’s difficult to change other persistence schemes.

And unfamiliarCoreDataI don’t want to know and study deeplyCoreDataI think that’s a big reason. So it is used in the projectCoreDataNot many people, but really masterCoreDataFewer people are skilled.

Listen to others beforeCoreDataLess efficient executionSQLiteGao, if you go deep, it’s trueCoreDataRatioSQLiteIt’s less efficient, but it doesn’t make much difference.CoreDataIt’s also implemented at the bottomSQLStatement, justCoreDataOfSQLStatement execution logic is time-consuming and not written manuallySQLStatement is more direct. We canCoreDataThe debugging function of is turned on. Take a look at itSQLStatement execution.

Let’s say that the client is not the server after all, and does not need to query as much data as the server, soCoreDataIt can completely deal with the query volume of the client. In terms of flexibility,CoreDataNot really.SQLiteHigh flexibility, someSQLiteBut for most projects today,CoreDataIt has been able to meet the requirements of project persistence.

The reason for the difference in execution efficiency is also reflected in the object transformation,CoreDataIn executionSQLOn the basis of the statement, there is another layer to map the data to the operation of managed object, so the result isOC, andSQLiteWhat you get is not. If givenSQLiteAfter execution, add a layer to create managed objects and assign values. At this time, the difference between the two may be smaller.

performance evaluation

Here is an article aboutCoreDataFMDBRealmPerformance test results blog, the final results I did not go to verify, but roughly looked at the code or price match. The author tests demo and the original address.

The number of test data is in K, with a minimum of 1K. The operations involved are mainly as follows

  1. New database and insert1KBar data.
  2. Existing database, inserting1KBar data.
  3. The total number of queries is10KData, continuous query single time is1KData.
  4. 10KTotal number of data, among which1KPartial field performance of data.
Performance evaluation results:

According to the test results, we can find that in the first two kinds of insertion operations,CoreDataPerformance ratioFMDBandRealmIt’s a lot faster.

For query operations,CoreDataIt takes a lot more time than the other two operations, about three or four times more. It’s very likelyCoreDataIt is related to converting the data of the query result to the managed object, and it is discardedCoreDataThis part of conversion operation performance will be much better than now.

The update operation is directly based onSQLiteEncapsulatedFMDBThere are absolute advantages,FMDBThe difference between the other two operations is about ten times, while the other two operations have similar performance. Of courseCoreDataThere are also object transformation operations mentioned above,CoreDataIt’s probably a lot better than it is.

Test chart

In the following test data, the average of the three test results is obtained.

The third party number
CoreData 1
Realm 3

Create a new database and insert 1K pieces of data

Meet coredata - get to know coredata

Existing database, 1K data inserted

Meet coredata - get to know coredata

The total number of queries is 10K pieces of data, and the number of consecutive queries is 1K pieces of data

Meet coredata - get to know coredata

Total 10K pieces of data, update the performance of some fields of 1K pieces of data

Meet coredata - get to know coredata

Coredata debugging

Xcode debug command

CoreDataIt’s essentially rightSQLiteAn encapsulation that internally transforms the persistence of objects intoSQLStatement execution, you canCoreDataDebugging is on so you can seeCoreDataOfSQLStatement execution and some otherslogInformation.

  1. openProductChooseEdit Scheme.
  2. ChoiceArguments, belowArgumentsPassed On LaunchAdd the following two options to.
Terminal debugging command

If you are debugging the program on the simulator, you can use theSQLite3 / database path/Command to view and manipulate the database.
.tablesView all table names in the current database file
select *from tableNameTo execute a querySQLSentence

Meet coredata - get to know coredata

Many students asked me that I hadDemoNo, in fact, the code posted in the article is a combination ofDemo。 After thinking about it, I still gave this series a simpleDemo, which is convenient for you to run and debug. In the future, all blog articles will be addedDemo

DemoJust to help readers better understand the content of the article,Should blog combineDemoStudy together, just watchDemoStill can’t understand the deeper principleDemoAlmost every line of code in will have a comment. You can break it and followDemoGo through the execution process to see the values of variables in each phase.

Demo address: Liu Xiaozhuang’s GitHub

The article has been updated in the past two daysCoreDataThe six articles in the series are integrated into onePDFVersion of coredata book, on my GitHub.PDFThere is a list of articles on it for easy reading.

If you think it’s good, please transfer PDF to other groups or your friends to let more people know coredata. Thank you!😁

Meet coredata - get to know coredata

Recommended Today

Spacemacs learning notes

install git clone ~/.emacs.d pacman -S emacs Change software source, edit.spacemacs, reference. Add the following code to the.spacemacsIndotspacemacs/user-init() (setq configuration-layer–elpa-archives ‘((“melpa-cn” . “”) (“org-cn” . “”) (“gnu-cn” . “”))) basic editing new file spc f f e path Save edits spc f s :w Close buffer spc b d Install the corresponding syntax extension […]