Using coredata for data persistence in IOS

Source: Internet
Author: User

Introduction:

Core DataYesIOSThe principle of the Data Persistence Solution Introduced after 3.0 isSQLiteIs not accessible to developers.SQLStatement to operate the database.

Its encoding method and principle structure are quite special. This blog post mainly introduces various problems encountered when using core data and explains its core principles.

References:

1: IOS Tutorial: Basic tutorial on persistent storage of core data

Http://www.dasheyin.com/ios_jiao_cheng_core_data_shu_ju_chi_jiu_xing_cun_chu_ji_chu_jiao_cheng.html

Installation:

The installation method is only one step.Coredata. FrameworkYou can.

Usage:

UseCore DataThe first class to be familiar with is the following:

1:Nsmanagedobjectmodel

2:Nspersistentstorecoordinator

3:Nsmanagedobjectcontext

It is also worth noting that if you do notUnderstandingThe three classes are implemented separately, so the code we see later has a very confused feeling:

Next we will introduce the specific functions and usage of each class:

1. nsmanagedobjectmodel (Manage object models (hereinafter referred to:Context):

Create a table structure, table field type, and the relationship between the table and the table (RelationshipAnd so on. All definitions related to the data structure are managed through this class.

To use this class, you needData Model(Data Model) files are used together, as shown in the following figure:

Then all of usData StructureThe definition and designData ModelTo complete.

In terms of code, you need to find it through the file path and initialize itNsmanagedobjectmodel

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Data Model Name" withExtension:@"momd"];self.keyManagedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

Note: NewData ModelThe file extension name after the file is data model name.XcdatamodeldHoweverXcodeCompile and packageAppLater, it will be converted into a data
Model name.MomdFile. The actual model file we want to add is the data model name.. MomdFile.

2.Nspersistentstorecoordinator(Persistent data coordinator ):

NspersistentstorecoordinatorIs true andSQLiteClass, mainly based onNsmanagedobjectmodelExecute the creation of the table structure throughNsmanagedobjectcontextCommand to execute Data Interaction
.

self.keyPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: self.keyManagedObjectModel];// handle db upgradeNSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,                         [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,                         nil];if (![self.keyPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]){}

Note: PassNsmanagedobjectmodelInitialization: Once the initialization is successful, the SQLite database has a complete table structure relationship, but this is not the focus of our attention. Continue.

3. nsmanagedobjectcontext(Manage object context)

NsmanagedobjectcontextIs the main interactive class in our development. The addition, deletion, modification, and query of Data triggers commands through context and returns results.NspersistentstorecoordinatorComplete Initialization

self.keyManagedObjectContext = [[NSManagedObjectContext alloc] init];[self.keyManagedObjectContext setPersistentStoreCoordinator:self.keyPersistentStoreCoordinator];

Here,CoredataThe preparation has been completed.XcodeTemplates can be directly completed.CoredataBut it is better for new users to understand it step by step so that they can find a solution in time when a bug occurs!

Next, start to manipulate the data!

Insert? Update one? Delete?

FamiliarSQLStatements: insert into table, update table, and delete table

InCoredata, All three work passesSaveFunction to complete, a function to complete three things, coredata so sharp?

Nspredicate(Condition adapter)

NspredicateMainlyNsfetchrequestThe service provides various condition statements for query, and filters out the data required by the compound service.

Listed below firstNspredicateSupported wildcard characters

1:Equal(=) Example: field = 'value'

2:Not equal(! =) Example: field! = 'Value'

3:Fuzzy(Like) Example: field like '* value *' or field like '? Value? 'Like usage? Represents one character, * represents multiple characters

4:Comparison(><=>=) Example: field> 6

The above four wildcards can be directly concatenated with strings. The following Wildcards are troublesome in String concatenation, but some code can be used to aid concatenation.

5:Range(Between) Example: field between {"6", "10 "}

You can run the following code to concatenate a conditional command:

NSArray *range = [[NSArray alloc]initWithObjects:@"6",@"10",nil];NSPredicate *betweenPredicate =[NSPredicate predicateWithFormat:@"field between %@", range];NSLog(@"%@",betweenPredicate.predicateFormat);

6:Include(IN) Example: filed in {"value1", "value2 "}
You can run the following code to concatenate a conditional command:

NSArray *choice = [[NSArray alloc]initWithObjects:@"value1",@"value2",nil];NSPredicate *inPredicate =[NSPredicate predicateWithFormat:@"filed in %@", choice];NSLog(@"%@",inPredicate.predicateFormat);

7:Compound(Or and not) Example: filed = "value2" or filed = "value3"

You can also splice the following code:

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"filed == 'value1'  "];NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"filed == 'value2' "];NSArray *predicates = [[NSArray alloc]initWithObjects:predicate1,predicate2,nil];NSPredicate *andCompoundPredicate =[NSCompoundPredicate orPredicateWithSubpredicates:predicates];

Before callingSaveWhat do I need to pay attention to when using functions?

An object only belongs to oneContextObject, so differentContextThe object under the jurisdiction cannot use oneContextTo call the Save method. This will only fail. The error message is as follows:

Illegal attempt to establish a relationship 'xyz' between objects in different contexts

Solution: (See stackoverflow ):

NSManagedObject *book = // get a book in one MOCNSManagedObject *owner = // get an owner in a different MOC[[owner mutableSetValueForKey:@"books"] addObject:[owner managedObjectContext:objectWithID:[book objectID]]];

Persistent store Coordinator: You can think of this as a database connection database. Here, you will set the name and location of the data storage and the timing of data storage.
Managed object context (manage data content): You can regard this part as the actual content of the data, which is also the most important part of the entire database (this is also used ), basically, data insertion, query, and deletion are all completed here.

Nsfetchrequest * request = [[nsfetchrequest alloc] init];
[Request setentity: entity]; [Request setresulttype: nsmanagedobjectidresulttype];
[Request setfetchbatchsize: 20];
Nserror * error = nil;
Nsarray * items = [context executefetchrequest: Request error: & error];
For (nsmanagedobjectid * objectid in items ){
Nsmanagedobject * object = [context objectwithid: objectid];
...}

Countforfetchrequest: Error

1: Relationship between the table and the table build tutorial http://blog.csdn.net/fengsh998/article/details/8123392

2: The solution is compatible with the old coredata database version when the application is upgraded and the table structure is changed. problem: When you add coredata to the project and start the app, everything works well, but the data structure of coredata is modified during development, such as adding or deleting a field, or a new table is added. when you run the app again, the app directly crash is found. how to solve the problem: coredata cannot modify the table structure from time to time, but coredata can handle the crash problem when the data structure changes in the form of multiple replicas. elaborate on the principle: the principle is similar to that of SVN which requires a tag. After a tag is added, the code of this version is no longer allowed to be modified. If you need to modify the code, it needs to be implemented in a new branch. after using the development tool to create a coredata management File: femicrocoopmodel. xcdatamodeld has only one branch by default. the method for adding a branch is as follows: 1. IDE-> Editor-> Add model version... 2. the following page is displayed: two fields: version name (take as needed) based on model: Basic Model (select an existing branch, inherited concept) after finishing, all new data structure modifications should be performed on this file. after modification, you need to set the versioned core data model (versioned Core Data Model) of the coredata management file, for example: only in this way will the application migrate data and modify the table structure according to the new data structure. in terms of code, there are only two points to note: 1. Add the adaptive configuration for the data structure version. The Code is as follows:

// handle db upgradeNSDictionary *options =[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,nil];

2: to instantiate an nsmanagedobjectmodel object, you need to input the model name. Here, you only need to specify the name when you first created the coredata management object. 3: enables the console to output SQL statements executed by core data. add a value for edit scheme-run-arguments:

-com.apple.CoreData.SQLDebug 1

As shown in:

3: Warning and Error 1: has no children warning prompt: solution: Clear the check box in the figure and compile it.

Summary:

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.