Basic use of core data

Source: Internet
Author: User
I. Introduction

Core data is a framework that emerged after ios5. It provides the object-relational ORM ing (ORM) function, that is, it can convert OC objects into data and store them in SQLite database files, it can also restore the data stored in the database to an OC object. During this data operation, we do not need to write any SQL statements. This is a bit similar to the famous Hibernate Persistence framework, but it certainly does not have the powerful functions of hibernate. Briefly describe its role:

On the left is the relational model, that is, the database. There is a person table in the database. The person table contains three fields: ID, name, and age, and there are two records;

The object model is on the right. We can see that there are 2 oC objects;

Using the core data framework, we can easily convert two records in the database into two OC objects, or store two OC objects in the database, it is converted into two table records without the need to write an SQL statement.

 

Ii. Model filesIn core data, the object to be mapped is called the entity. In addition, you must use the model file of core data to describe all the entity and object attributes in the app. Here we use two entities: person and card. First, let's look at the associations between object attributes and objects:

The person entity has three attributes: name, age, and card.
The card entity has two attributes: No (number) and person (person ).

Next let's take a look at the process of creating a model file:
1. Select a template


2. Add an object


3. Add two basic attributes of person


4. Add one basic attribute of the card



5. Establish the association between card and person

The picture in the right shows that the card has a person-type person attribute. The purpose is to establish a one-to-one relationship between the card and the person (we suggest adding this item). After adding the inverse attribute to the person, you will find that the inverse attribute in the card is automatically added.

 

3. Understand nsmanagedobject objects1. The objects retrieved from the database using core data are nsmanagedobject objects by default.


2. The nsmanagedobject working mode is somewhat similar to the nsdictionary object. It uses key-value pairs to access all object attributes.

1> setvalue: forkey: storage property value (attribute name: key)

2> valueforkey: Get the property value (the property name is key)

4. core objects in coredata
Note: Black indicates the class name, and red indicates an attribute in the class.
Summary of development steps:
1. initialize the nsmanagedobjectmodel object, load the model file, and read all object information in the app.
2. initialize the nspersistentstorecoordinator object and add the persistence Library (Here we use the SQLite database)
3. initialize the nsmanagedobjectcontext object, obtain the context object operation entity, and perform the CRUD operation. V. Code ImplementationAdd coredata. Framework and import the main header file <coredata/coredata. h>


1. Set up the context
  1. // Load the model file from the application package
  2. Nsmanagedobjectmodel * model = [nsmanagedobjectmodel mergedmodelfrombundles: Nil];
  3. // Input the model object and initialize nspersistentstorecoordinator
  4. Nspersistentstorecoordinator * PSC = [[nspersistentstorecoordinator alloc] initwithmanagedobjectmodel: Model] autorelease];
  5. // Construct the path of the SQLite database file
  6. Nsstring * docs = [nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) lastobject];
  7. Nsurl * url = [nsurl fileurlwithpath: [docs stringbyappendingpathcomponent: @ "person. Data"];
  8. // Add a persistent repository. SQLite is used as the repository here.
  9. Nserror * error = nil;
  10. Nspersistentstore * store = [PSC addpersistentstorewithtype: nssqlitestoretype configuration: Nil URL: URL options: Nil error: & error];
  11. If (store = nil) {// directly throw an exception
  12. [Nsexception raise: @ "add database error" Format: @ "% @", [error localizeddescription];
  13. }
  14. // Initialize the context and set the persistentstorecoordinator attribute
  15. Nsmanagedobjectcontext * context = [[nsmanagedobjectcontext alloc] init];
  16. Context. persistentstorecoordinator = PSC;
  17. // After running out, remember to [context release];

2. Add data to the database
  1. // Input context to create a person object
  2. Nsmanagedobject * person = [nsentitydescription insertnewobjectforentityforname: @ "person" inmanagedobjectcontext: Context];
  3. // Set simple attributes of person
  4. [Person setvalue: @ "mj" forkey: @ "name"];
  5. [Person setvalue: [nsnumber numberwithint: 27] forkey: @ "Age"];
  6. // Input context to create a card object
  7. Nsmanagedobject * card = [nsentitydescription insertnewobjectforentityforname: @ "card" inmanagedobjectcontext: Context];
  8. [Card setvalue: @ "4414241933432" forkey: @ "no"];
  9. // Set the relationship between person and card
  10. [Person setvalue: Card forkey: @ "card"];
  11. // Use the context object to synchronize data to the persistent Repository
  12. Nserror * error = nil;
  13. Bool success = [context save: & error];
  14. If (! Success ){
  15. [Nsexception raise: @ "database access error" Format: @ "% @", [error localizeddescription];
  16. }
  17. // If you want to update the object, you can synchronize the changed data to the database by calling [context save: & error] After modifying the object attributes.

3. query data from the database
  1. // Initialize a query request
  2. Nsfetchrequest * request = [[nsfetchrequest alloc] init] autorelease];
  3. // Set the object to be queried
  4. Request. entity = [nsentitydescription entityforname: @ "person" inmanagedobjectcontext: Context];
  5. // Set sorting (by age in descending order)
  6. Nssortdescriptor * sort = [nssortdescriptor sortdescriptorwithkey: @ "Age" ascending: No];
  7. Request. sortdescriptors = [nsarray arraywithobject: Sort];
  8. // Set the condition filter (search for records whose name contains the string "Itcast-1", note: when setting the condition filter, % in the Database SQL statement should be replaced, so % Itcast-1 % should be written as * Itcast-1 *)
  9. Nspredicate * predicate = [nspredicate predicatewithformat: @ "name like % @", @ "* Itcast-1 *"];
  10. Request. predicate = predicate;
  11. // Execute the request
  12. Nserror * error = nil;
  13. Nsarray * objs = [context executefetchrequest: Request error: & error];
  14. If (error ){
  15. [Nsexception raise: @ "query error" Format: @ "% @", [error localizeddescription];
  16. }
  17. // Traverse data
  18. For (nsmanagedobject * OBJ in objs ){
  19. Nslog (@ "name = % @", [OBJ valueforkey: @ "name"]
  20. }
Note: core data does not immediately obtain the associated object based on the association relationship in the object. For example, when the person object is retrieved using core data, it does not immediately query the associated card object; when the application really needs to use card, it will query the database again and load the card object information. This is the latency Loading Mechanism of core data.

4. delete data from the database
  1. // Input the object to be deleted
  2. [Context deleteobject: managedobject];
  3. // Synchronize the result to the database
  4. Nserror * error = nil;
  5. [Context save: & error];
  6. If (error ){
  7. [Nsexception raise: @ "delete error" Format: @ "% @", [error localizeddescription];
  8. }

 

6. Enable the SQL statement output of coredata1. Open product and click editscheme...
2. Click arguments and add two items in argumentspassed on launch.
1>-Com. Apple. coredata. sqldebug
2> 1

7. Create a subclass of nsmanagedobjectBy default, all objects retrieved using core data are of the nsmanagedobject type and can be accessed using key-value pairs. However, in general, when an object accesses data, it sometimes needs to add some business methods to complete some other tasks, so it is necessary to create a subclass of nsmanagedobject.


Select model file


Select the object to create a subclass


After creation, two more child classes are added.


File Content display:
Person. h
  1. # Import <Foundation/Foundation. h>
  2. # Import <coredata/coredata. h>
  3. @ Class card;
  4. @ Interface person: nsmanagedobject
  5. @ Property (nonatomic, retain) nsstring * Name;
  6. @ Property (nonatomic, retain) nsnumber * age;
  7. @ Property (nonatomic, retain) card * card;
  8. @ End

Person. m
  1. # Import "person. H"
  2. @ Implementation person
  3. @ Dynamic name;
  4. @ Dynamic age;
  5. @ Dynamic card;
  6. @ End

Card. h
  1. # Import <Foundation/Foundation. h>
  2. # Import <coredata/coredata. h>
  3. @ Class person;
  4. @ Interface Card: nsmanagedobject
  5. @ Property (nonatomic, retain) nsstring * No;
  6. @ Property (nonatomic, retain) person * person;
  7. @ End

Card. m
  1. # Import "card. H"
  2. # Import "person. H"
  3. @ Implementation card
  4. @ Dynamic no;
  5. @ Dynamic person;
  6. @ End

When adding data to the database, you should write:
  1. Person * person = [nsentitydescription insertnewobjectforentityforname: @ "person" inmanagedobjectcontext: Context];
  2. Person. Name = @ "mj ";
  3. Person. Age = [nsnumber numberwithint: 27];
  4. Card * card = [nsentitydescription insertnewobjectforentityforname: @ "card" inmanagedobjectcontext: Context];
  5. Card. No = @ "4414245465656 ";
  6. Person. Card = card;
  7. // Call [context Save & error] To save the data


Speaking of this, the entire core data framework is over. In fact, core data is far more than these functions. It also supports automatic revocation and one-to-Multiple Association.

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.