A summary of the basic data management functions of the core information framework in IOS app development _ios

Source: Internet
Author: User

First, what is CoreData
CoreData is a framework for managing data that has great advantages in both performance and writing, and in database management, Apple strongly recommends that developers use the CoreData framework, said in Apple's official document, While it's a bit exaggerated to use the CoreData framework to reduce the amount of code that developers 50%--70%, CoreData is really powerful.

II. Design Data Model
in iOS development, a large number of table-structured data is often processed using SQL databases, but SQL has a very obvious flaw, for the regular data model of the table, it is not a problem to deal with, such as a class table, where each of the data has class name, number of such attributes, a student table, Each of these data has attributes such as the student's name, gender, and age. However, if you want to make a connection between tables and tables, custom objects have a dependency relationship with custom objects, which can be cumbersome to use with SQL, for example, if the class table has a class monitor attribute, this property is a student type.
1. Create entity types and their attributes
Create a project using Xcode, create a new file in the project, select Datamodel in the core data category, and the following figure:

At this point in the Xcode file navigation area will appear a xcdatamodeld file extension, this file is the data model file, click the Add Entity button to add an entity type, named Schoolclass, add two attributes for this type, Name and number of students Stunum, respectively, as shown below:

2. Set the entity type
The entity type can be set on the toolbar on the right side of Xcode to select an entity type, as shown in the following figure:

Name sets the names of the entity types, and if checked, the entity cannot be instantiated and can only be inherited, similar to an abstract class, such as the definition of an entity type, a teacher, student, etc. that is defined as inheriting from the human entity type. Parent entity is used to select the parents class entity, class is used to set the corresponding class.

3. Establishing relationships between entity objects
then create a student class entity student and add the name and age two properties. Select Schoolclass and click the + number in the Relationships module to add a relationship, as shown below:

At this point, the Schoolclass entity type has a student type of Class monitor attribute. If you switch the editing style, you can see the relationship between the entity types more clearly, as shown in the following figure:

4. Setting properties and Relationships
to select a property or relationship, you can set the properties in the toolbar on the right, as shown in the following figure:

Name setting property, optional type is optional, that is, you can assign or not assign a value when instantiating an object. Attribute sets the data type of the property, and default value sets the defaults for the data.
second, data Model Management class Nsmanagedobjectmodel

By Nsmanagedobjectmodel, you can read the created data Model file as a Model Management class object, using the following methods:
//获取.xcdatamodeld文件url
NSURL *modelUrl = [[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"];
//读取文件
NSManagedObjectModel * mom = [[NSManagedObjectModel alloc]initWithContentsOfURL:modelUrl];
There are also some properties and methods for managing the data model:

Merging multiple data Model Management files
+ (Nullable Nsmanagedobjectmodel *) Mergedmodelfrombundles: (Nullable nsarray<nsbundle *> *) bundles;
Merging multiple data Model Management class objects
+ (Nullable Nsmanagedobjectmodel *) Modelbymergingmodels: (Nullable Nsarray<nsmanagedobjectmodel *> *) models;
The dictionary Dictionary of all entity models in the data is the entity name and entity description Object
@property (readonly, copy) nsdictionary<nsstring *, nsentitydescription *> *entitiesbyname;
Holds all entity description objects in the data
@property (Strong) nsarray<nsentitydescription *> *entities;
Return all available configuration names
@property (ReadOnly, strong) nsarray<nsstring *> *configurations;
Get all entities associated with a configuration
-(Nullable nsarray<nsentitydescription *> *) Entitiesforconfiguration: (Nullable NSString *) configuration;
Associating a configuration for an entity
-(void) Setentities: (nsarray<nsentitydescription *> *) entities forconfiguration: (NSString *) configuration;
Create a request template
-(void) Setfetchrequesttemplate: (Nullable nsfetchrequest *) fetchrequesttemplate forname: (NSString *) name;
Get request Template
-(Nullable Nsfetchrequest *) Fetchrequesttemplateforname: (NSString *) name;
About Entity Description Object nsentitydescription:

An entity resembles a table structure in a database, such as the class entity model that we created last time, a lot of attributes and relationships can be added to an entity model, and the information is stored in Nsentitydescription objects, often as follows:

Model Management object in which the entity resides
@property (readonly, assign) Nsmanagedobjectmodel *managedobjectmodel;
The name of the Model Management object in which the entity resides
@property (null_resettable, copy) NSString *managedobjectclassname;
Entity Name
@property (nullable, copy) NSString *name;
Set whether it is an abstract entity
@property (getter=isabstract) BOOL abstract;
Subclass Entity Dictionary
@property (readonly, copy) nsdictionary<nsstring *, nsentitydescription *> *subentitiesbyname;
Array of all subclass entity objects
@property (Strong) nsarray<nsentitydescription *> *subentities;
Parent class Entity
@property (Nullable, ReadOnly, assign) Nsentitydescription *superentity;
All Properties Dictionaries
@property (readonly, copy) nsdictionary<nsstring *, __kindof nspropertydescription *> *propertiesbyname;
All property Arrays
@property (Strong) Nsarray<__kindof nspropertydescription *> *properties;
All constant Type properties
@property (readonly, copy) nsdictionary<nsstring *, nsattributedescription *> *attributesbyname;
All relationships
@property (readonly, copy) nsdictionary<nsstring *, nsrelationshipdescription *> *relationshipsbyname;
All relationships for an entity type
-(nsarray<nsrelationshipdescription *> *) relationshipswithdestinationentity: (NSEntityDescription *) entity;
To determine whether it is an entity
-(BOOL) iskindofentity: (nsentitydescription *) entity;
The Nspropertydescription class is the parent class of the data model properties, Nsattributedescription and Nsrelationshipdescription are inherited from the Nspropertydescription class, Nsattributedescription describes the properties of the normal type, nsrelationshipdescription is used to describe the relationship of the custom type.

III. Persistent Storage Coordinator Class Nspersistentstorecoordinator

Nspersistentstorecoordinator establishes a connection between a data model and a local file or database, by which local data is read into memory or the modified temporary data is persisted. Its initialization and link data persistence object methods are as follows:

//通过数据模型管理对象进行初始化
- (instancetype)initWithManagedObjectModel:(NSManagedObjectModel *)model;
//添加一个持久化的数据接收对象
- (nullable __kindof NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(nullable NSString *)configuration URL:(nullable NSURL *)storeURL options:(nullable NSDictionary *)options error:(NSError **)error;
//移除一个持久化的数据接收对象
- (BOOL)removePersistentStore:(NSPersistentStore *)store error:(NSError **)error;

Iv. data Object Management Context Nsmanagedobjectcontext

Nsmanagedobjectcontext is the core of data management, we use this class to do the data additions and deletions to check the operation. The common methods are as follows:

The initialization method initializes the parameter with a concurrent type as follows:
/*
typedef ns_enum (Nsuinteger, Nsmanagedobjectcontextconcurrencytype) {
Nsprivatequeueconcurrencytype = 0x01,//Context object is associated with a private queue
Nsmainqueueconcurrencytype = 0x02//Context object associated with the primary queue
};
*/
-(Instancetype) Initwithconcurrencytype: (nsmanagedobjectcontextconcurrencytype) CT;
Execute block asynchronously
-(void) Performblock: (void (^) ()) block;
Synchronous execution Block
-(void) performblockandwait: (void (^) ()) block;
Associating data persistence objects
@property (nullable, strong) Nspersistentstorecoordinator *persistentstorecoordinator;
Is there any uncommitted changes
@property (nonatomic, readonly) BOOL haschanges;
Querying for data requests
-(Nullable Nsarray *) Executefetchrequest: (nsfetchrequest *) Request Error: (NSERROR * *) error;
Request for query Data bar number
-(Nsuinteger) Countforfetchrequest: (nsfetchrequest *) Request Error: (NSERROR * *) error;
inserting elements
-(void) InsertObject: (Nsmanagedobject *) object;
Delete Element
-(void) DeleteObject: (Nsmanagedobject *) object;
Roll back one Step
-(void) undo;
Clear Cache
-(void) reset;
Restore data
-(void) rollback;
Submit Save Data
-(BOOL) Save: (nserror * *) error;

Related Article

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.