This article belongs to the original of “Jianshu Liu Xiaozhuang”. Please indicate:
< Jianshu Liu Xiaozhuang > http://www.jianshu.com/p/c0e12a897971
`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 objc.io 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
Written in front
CoreDataThere 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。
.xcdatamodeldBecause it stores the data structure and representation of all entities, it is calledModel file。
What is coredata?
A brief introduction
iOS3Is a data storage framework introduced by apple.
CoreDataProvides an object relation mapping（
ORM）, similar to
JavaThe Hibernate framework of.
OCObjects are stored in the database, or data in the database can be converted to
OCObject, no manual writing is required during this process
SQLStatement, this is the system to help us complete.
CoreDataThe biggest advantage is that there is no need to write any
CoreDataIt encapsulates the operation process of the database, as well as the data and
OCObject. So we are using
CoreDataIn the process, many operations are just like database operations, including filtering conditions, sorting and other operations.
This is equivalent to
ModelLayer, for example
ModelThe representation and persistence of layer can effectively reduce the workload of development and make
ModelLayer 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 say
CoreDataOne 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 mastered
In terms of performance,
SQLiteIt’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 show
CoreDataComparison of advantages and disadvantages, as well as detailed performance evaluation.
Several main classes of coredata
Managed object contextMost of the data operations are related to this class.
Managed object model, a managed object model is associated with a model file（
.xcdatamodeld）, which stores the data structure of the database.
Persistent storage coordinator, which is responsible for coordinating the relationship between the store and the context.
Managed object classAll
CoreDataAll managed objects in must inherit from the current class and create a managed object class file based on the entity.
Coredata simple creation process
- 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 on
NSManagedObjectClass file of)
- Instantiate context object
2.1 create managed object context（
2.2 create managed object model（
2.3 create persistent storage coordinator according to managed object model（
2.4 associate and create local database files and return persistent storage objects（
2.5 assign the persistent storage coordinator to the managed object context to complete the basic creation.
The structure of coredata
I saw several introductions before
CoreDataThe structure of the picture, feel the structure of the expression is relatively clear. We can get to know each other through these pictures
CoreData, which will be explained in detail in later articles.
Initialization is shown in the figure above
MOCSome of the classes involved are instantiated by these classes and finally constitute usable
MOC。 The number in the figure is an instantiation with data processing capability
MOCProcedure, which is the same as the instantiation context object described above.
PSCCreate and associate a local database and set to
persistentStoreCoordinatorAfter 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 the
MOCIn the cache of.
MOMAfter the object loads the model file, get the structure of all the entities in the model file. Because
MOMThe structure of the model file is stored in,
PSCNeed to pass
MOMObject instantiates the local database.
All properties exist
Entity, as well as the related properties and request templates, which will be discussed in the following chapters.
EntityCreate inheritance from
NSManagedObjectClass. 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
CoreDataThere are two parts in the whole structure. One is
NSManagedObjectContextThe model part of management, which manages all
CoreDataManaged object for. One is
SQLiteThe local persistence part of the implementation, responsible for and
SQLData exchange is mainly conducted by
NSPersistentStoreClass operations. That’s what it’s made of
CoreDataThe general structure of.
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 strata
NSManagedObjectContextThe 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.
CoreDataThe underlying storage is used
SQLiteRealized, so I used
SQLiteBy contrast, we find that there are many similarities.
.xcdatamodeldThe file represents the file structure of the database
.momdFile generation database. Each entity represents a data table. The relationship between entities is
SQLiteThe 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 example
1The primary key subscript pointing to the associated table is
Coredata data storage security
CoreDataNature or use
SQLiteFor 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：
SQLiteAfter 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_MODELCACHEOther watches of our ownUppercase ZThe first.
In each table, three fields are generated by default,
Z_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 use
SQLiteAs a durable solution, and
CoreDataThe use of is not very common. For this problem, I think the first thing is that many projects started earlier, at that time many
iOSProgrammers are more familiar with other languages
SQLiteMore. If we don’t do large project refactoring later, it’s difficult to change other persistence schemes.
CoreDataI don’t want to know and study deeply
CoreDataI think that’s a big reason. So it is used in the project
CoreDataNot many people, but really master
CoreDataFewer people are skilled.
Listen to others before
CoreDataLess efficient execution
SQLiteGao, if you go deep, it’s true
SQLiteIt’s less efficient, but it doesn’t make much difference.
CoreDataIt’s also implemented at the bottom
SQLStatement execution logic is time-consuming and not written manually
SQLStatement is more direct. We can
CoreDataThe debugging function of is turned on. Take a look at it
Let’s say that the client is not the server after all, and does not need to query as much data as the server, so
CoreDataIt can completely deal with the query volume of the client. In terms of flexibility,
SQLiteHigh flexibility, some
SQLiteBut 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,
SQLOn the basis of the statement, there is another layer to map the data to the operation of managed object, so the result is
SQLiteWhat you get is not. If given
SQLiteAfter execution, add a layer to create managed objects and assign values. At this time, the difference between the two may be smaller.
Here is an article about
RealmPerformance 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：
- New database and insert
- Existing database, inserting
- The total number of queries is
10KData, continuous query single time is
10KTotal number of data, among which
1KPartial field performance of data.
Performance evaluation results:
According to the test results, we can find that in the first two kinds of insertion operations,
RealmIt’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 likely
CoreDataIt is related to converting the data of the query result to the managed object, and it is discarded
CoreDataThis part of conversion operation performance will be much better than now.
The update operation is directly based on
FMDBThere are absolute advantages,
FMDBThe difference between the other two operations is about ten times, while the other two operations have similar performance. Of course
CoreDataThere are also object transformation operations mentioned above,
CoreDataIt’s probably a lot better than it is.
In the following test data, the average of the three test results is obtained.
|The third party||number|
Create a new database and insert 1K pieces of data
Existing database, 1K data inserted
The total number of queries is 10K pieces of data, and the number of consecutive queries is 1K pieces of data
Total 10K pieces of data, update the performance of some fields of 1K pieces of data
Xcode debug command
CoreDataIt’s essentially right
SQLiteAn encapsulation that internally transforms the persistence of objects into
SQLStatement execution, you can
CoreDataDebugging is on so you can see
SQLStatement execution and some others
ArgumentsPassed On LaunchAdd the following two options to.
Terminal debugging command
If you are debugging the program on the simulator, you can use the
SQLite3 / database path/Command to view and manipulate the database.
.tablesView all table names in the current database file
select *from tableNameTo execute a query
Many students asked me that I had
DemoNo, in fact, the code posted in the article is a combination of
Demo。 After thinking about it, I still gave this series a simple
Demo, which is convenient for you to run and debug. In the future, all blog articles will be added
DemoJust to help readers better understand the content of the article,Should blog combine
DemoStudy together, just watch
DemoStill can’t understand the deeper principle。
DemoAlmost every line of code in will have a comment. You can break it and follow
DemoGo 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 days
CoreDataThe six articles in the series are integrated into one
If you think it’s good, please transfer PDF to other groups or your friends to let more people know coredata. Thank you!😁