CoreData of iOS data storage

Source: Internet
Author: User

Storage of large amounts of data in iOS one is SQLite, and the other is coredata,coredata allows programmers to manipulate table-oriented databases in an object-oriented way of thinking

Java has been developed for this should be very familiar with, in Java, Hibernate and CoreData are very similar

How should coredata be used?

The first step is to import the CoreData framework after the new project

Second, create the CoreData data model with the following steps

Then give your model a name and you'll see a file (equivalent to a database file) when you're done creating it.

Click this file, and then look

Click on Figure 1, create a new entity (similar to a table in the Data Bureau Library),,, then name the entity 2 in the diagram, and then add a field (similar to the column name in the database) to your entity in three positions in the diagram.

The first is to build the table inside the database, to manipulate the table through the class object, but also need to have the corresponding object

Next, create the corresponding object, create the CoreData object is different from the usual we create NSObject object, CoreData object is created by the tool;

Follow the way in the diagram, next, and then you'll find that you have two files in your directory tree with the same name as your entity name

Now that we've finished working on the basic tools for using coredata, we're going to start writing code.

To manipulate the CoreData file in code, a context object (similar to a handle in SQL) is required

Nsmanagedobjectcontext *sharedcontext;

When we created the CoreData file, the program ran, and the app created some files in the Mainbundle, which correspond to the created model

, to manipulate one or more models, you need to combine the files with code, and the following is the merged code

Nsmanagedobjectmodel *model = [Nsmanagedobjectmodel Mergedmodelfrombundles:nil];

Then the data file table and object building relationship requires a central dispatcher,

Central Dispatch This can establish the correspondence between the database and the object and the model file.

The corresponding code is as follows

Nspersistentstorecoordinator *coordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel: Model];    [Coordinator Addpersistentstorewithtype:nssqlitestoretype Configuration:nil Url:[nsurl FileURLWithPath:path] Options:nil Error:nil];         = [[Nsmanagedobjectcontext alloc] init];     = Coordinator;

So far, we can happy the relationship between the context manipulation object and the database.

First, we'll look at how to insert an object data into the database

Because you want the object to be stored with the database, do not create the object with the previous alloc and Init

To use the method provided by the tool so that the system knows the connection between the object and the database

Person *per = [Nsentitydescription insertnewobjectforentityforname:@" Person"Inmanagedobjectcontext:[datamanager Shareddatamanager].sharedcontext]; Per.name=@"Jing"; Per.phoneno=@"123123123"; if([_sharedcontext Save:nil]) {NSLog (@"Yes"); }Else{NSLog (@"No"); }

This allows the per object to be stored in the database

Let's see how to get the data.

CoreData data is to go to the database to query data, and then return the data, so we need a query result controller (non-view controller)

Nsfetchedresultscontroller *_fetchedresultscontroller;

The code to execute the query is as follows

//Query RequestNsfetchrequest *request = [Nsfetchrequest fetchrequestwithentityname:@" Person"]; //Sort by user name ascendingNssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@"name"Ascending:yes]; Request.sortdescriptors=@[sort]; /** Parameters: 1> Query Request 2> database context 3> field name used for grouping in table 4> cache name*/_fetchedresultscontroller=[[Nsfetchedresultscontroller alloc] Initwithfetchrequest:request managedobjectcontext:context        Sectionnamekeypath:nil Cachename:nil]; //Set up proxy_fetchedresultscontroller.Delegate=Self ; //execute request, FETCH dataNserror *error =Nil; if([_fetchedresultscontroller performfetch:&ERROR]) {NSLog (@"Query Successful"); NSLog (@"%@", _fetchedresultscontroller.sections); } Else{NSLog (@"Query failed%@", error.localizeddescription); }

Creating a query result controller requires a query request (similar to urlrequest in a Web request) and the context to query

Query request needs to write the name of the query model, and also need to set a sort of rules Nssortdescriptor object (can be set to sort multiple fields)

When creating a query result controller Sectionnamekeypath, interested can be studied, this can be used to group the query data (passing nil means that all the data in a group)

The above code just lets the query result controller go to the database inside to look for, how to take out the data from the result controller?

Person *person = [_fetchedresultscontroller Objectatindexpath:indexpath];

The above code can take out the results of the query, look at it is not very familiar with tableview some of the methods are not very similar ~, you look at the following code

int total =  [_fetchedresultscontroller.sections[0] numberofobjects];

The above code can return the total number of data contained in the NO. 0 set of data, whether it feels more like TableView

This is the end of the query, and here's a look at how to delete an object

// Let context delete         [Context Deleteobject:person];                 // Context Save        if ([context Save:nil]) {            NSLog (@ " Delete succeeded! ) " );         Else {            NSLog (@ " Delete failed! ) " );        }

The above sentence will be fixed ~ How to modify the object?

@" Wokao " ;   if ([context Save:nil]) {        NSLog (@ " Save succeeded ");                 // return to the ancestor View Controller         [Self.navigationcontroller popviewcontrolleranimated:yes];     Else {        NSLog (@ " save failed! ) " );    }

Modify the objects directly on the object you want to modify, and then save on the line, ~ ╮(╯▽╰)╭ is not wood pressure?

There is also a problem is the query to a lot of results, how to filter it? You found 100 results, but only 10 are what you see, what do you do?

Table Anxious ~ There is a way ~

 //1. Get the query request to the query results controllerNsfetchrequest *reqest =_fetchedresultscontroller.fetchrequest; if(Searchtext.length >0) {        //Set the filter predicate for the requestReqest.predicate = [Nspredicate predicatewithformat:@"name CONTAINS%@", SearchText]; } Else{reqest.predicate=Nil; }        //Execute Query    if([_fetchedresultscontroller Performfetch:nil]) {NSLog (@"Refresh succeeded");    [Self.tableview Reloaddata]; }

In fact, the filter is to give the query results of the controller's request is taken out, add a predicate in ~ and then re-execute the query on the line ~

If you want to revert to the original query results, request.predicate = nil, and then re-query on the line ~

jiandannnnnnnn BA

In addition, CoreData can easily store binary data, if you want to use SQL to store binary data what the estimate will be a bit harder, and write very likely or slow down your query performance

The following line of code can convert a UIImage object to a NSData object

Uiimagepngrepresentation (_iconbutton.imageview.image);

You'll find it later, ~~~~~~.

There's also a photo selector controller

Uiimagepickercontroller

As for how to use, to check the information yourself ~

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.