An explanation of the creation of IOS CoreData database

Source: Internet
Author: User
Tags sqlite database

CoreData Database Introduction CoreData Introduction

CoreDatais a powerful data persistence technology located on the SQLite database, which avoids the complexity of SQL and allows us to interact with the database in a more natural way. CoreData provides data--oc object mapping relationships for data and object management so that you can manipulate them without any SQL statements.
CoreDataThe data persistence Framework is Cocoa API part of the iOS5 version of the system, which allows data to be persisted in accordance with--organizing the data and/ 实体 属性 值模型 XML ?进制文件 or SQLite数据?件 formatting it.

Compare CoreData with SQLite

Sqlite

1、基于C接口,需要使用SQL语句,代码繁琐2、在处理大量数据时,表关系更直观3、在OC中不是可视化,不易理解

CoreData

1、可视化,且具有undo/redo能力2、可以实现多种文件格式:    NSSQLiteStoreType    NSBinaryStoreType    NSInMemoryStoreType    NSXMLStoreTyp3、苹果官方API支持,与iOS结合更紧密
CoreData Core class and structure

NSManagedObjectContext(Data context)

    • Object management context, which is responsible for the actual operation of the data (important)
    • Role: Inserting data, querying data, deleting data, updating data

NSPersistentStoreCoordinator(Persistent storage assistant)

    • A connector equivalent to a database
    • Role: Set the name, location, storage, and storage time of the data store

NSManagedObjectModel(Data Model)

    • Database all tables or data structures containing the definition information for each entity
    • Role: Adding attributes to entities, establishing relationships between attributes
    • How to: View Editor, or code

NSManagedObject(Managed data record)

    • Table records in the database

NSEntityDescription(Entity structure)

    • Equivalent to table structure

NSFetchRequest(Data request)

    • Equivalent to a query statement

后缀为.xcdatamodeldThe package

    • Inside is the. xcdatamodel file, which is edited with the Data Model Editor
    • Compiled for. MOMD or. Mom Files

Diagrams between categories


Diagrams between categories CoreData database manually created

Create the steps below

1.创建模型文件 [相当于一个数据库]2.添加实体 [一张表]3.创建实体类 [相当模型--表结构]4.生成上下文 关联模型文件生成数据库
0. Create the Project

1. When creating CoreData data manually, we create a common and peaceful project that does not need to be checked Use Core Data :


Project creation 1, creating model files

1. Enter to create a new file, command+N or as


Create

2. Select a file type, such as:


Select file type

3, set the file name, such as:


Set file name

4, the model file created successfully, will appear later


Create a Success 2, create an entity

1, the use of visual way to create entities, the function of the entity is similar to our model class, the specific operation as follows:


Create entity 3, create entity class

Create entities with visualizations, but to get the corresponding data and names, we have to associate classes, so to create an entity class, create the following steps:

1. Enter to create a new file


Create a new file

2, select the file type, entity class file type selection:NSManagedObject subclass


Create an entity class

3. Select Model file


Select Model File

4. Select entity


Select entity

5. Successful creation


Entity Creation succeeded

After the creation of the entity files, the system automatically helps us to generate corresponding, corresponding 类和属性 类名 , corresponding 实体名称 属性 entities 属性名称 ; If our property is a basic data type, the default will help us convert to NSNumber a type of property.

* 老版本:只生成一对文件,即类和属性都在一起* 新版本:生成一对类文件,再生成一对类目,在类目中生成属性
4. Generate context Associated Database

Before creating the context and associated database, let's take a look at the relational dependency graph that we want to correspond to:


Dependency diagram

From what we see, to build the context, need to have 数据库助理 and 模型 support; just like in SQLite, you want to have and create a database, and you have to have 数据库 it, and we'll see the implementation code:

- (void) Viewdidload {[SuperViewdidload];///1, creating model objects    //Get model path    Nsurl*modelurl = [[NSBundleMainbundle] Urlforresource:@ "School"Withextension:@ "MOMD"];//Create model objects from model files    Nsmanagedobjectmodel*model = [[NsmanagedobjectmodelAlloc] Initwithcontentsofurl:modelurl];///2, create persistence assistant    //Create an Assistant object with a model object    Nspersistentstorecoordinator*store = [[NspersistentstorecoordinatorAlloc] Initwithmanagedobjectmodel:model];//The name and path of the database    NSString*DOCSTR = [Nssearchpathfordirectoriesindomains(nsdocumentdirectory,Nsuserdomainmask,YES) Lastobject];NSString*sqlpath = [Docstr stringbyappendingpathcomponent:@ "Mysqlite.sqlite"];NSLog(@ "path =%@", SQLPath);Nsurl*sqlurl = [NsurlFileurlwithpath:sqlpath];//Set up database related information[Store Addpersistentstorewithtype:NssqlitestoretypeConfigurationNilUrl:sqlurl options:NilErrorNil];///3, create context    Nsmanagedobjectcontext*context = [[NsmanagedobjectcontextAlloc] Initwithconcurrencytype:Nsmainqueueconcurrencytype];//Associate Persistence Assistant[Context Setpersistentstorecoordinator:store]; _context = context;}
    • After this, our entire CoreData database even if the creation is completed, the whole process is we manual, so as 原理 to better understand;
    • After running the database has been created to complete, into the corresponding path, we can see the database file has been created;
    • After using the tool to open, found that the corresponding table also helped us to create a good;
    • After the above steps have been created, in the subsequent work we do not need to do any database-related work, all the work with the database has been given to CoreData to achieve.
CoreData Database System creation

Using the system to create the database and manually create the same way internal steps, but the system will create model files, build context, the work of the associated database to help us do, these work we do not need to do;
Say so much, let's take a look at how to create a CoreData database using the system itself

It takes only two steps to create a system with its own:

    • Create a project
    • Create entity already associated entity class
Create a project

1, manually create CoreData a database, we create a peaceful common project, special attention: Be sure to tick Use Core Data :


Project creation

2, after the project is created, the system will automatically help us to create a project with the same name, and 模型文件 help us to write the 生成上下文 关联数据库 code:


Model file
Build context and associated database

Once these are done, we just need to create 实体 , and the association 实体类 can

Create Entity Association entity class

You create entities and associated entity classes in the 手动创建数据库 same way that you create them manually by referencing 2、3



Wen/tanyufeng (author of Jane's book)
Original link: http://www.jianshu.com/p/880dd63c5f5e
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

An explanation of the creation of IOS CoreData database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.