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
- // Load the model file from the application package
- Nsmanagedobjectmodel * model = [nsmanagedobjectmodel mergedmodelfrombundles: Nil];
- // Input the model object and initialize nspersistentstorecoordinator
- Nspersistentstorecoordinator * PSC = [[nspersistentstorecoordinator alloc] initwithmanagedobjectmodel: Model] autorelease];
- // Construct the path of the SQLite database file
- Nsstring * docs = [nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes) lastobject];
- Nsurl * url = [nsurl fileurlwithpath: [docs stringbyappendingpathcomponent: @ "person. Data"];
- // Add a persistent repository. SQLite is used as the repository here.
- Nserror * error = nil;
- Nspersistentstore * store = [PSC addpersistentstorewithtype: nssqlitestoretype configuration: Nil URL: URL options: Nil error: & error];
- If (store = nil) {// directly throw an exception
- [Nsexception raise: @ "add database error" Format: @ "% @", [error localizeddescription];
- }
- // Initialize the context and set the persistentstorecoordinator attribute
- Nsmanagedobjectcontext * context = [[nsmanagedobjectcontext alloc] init];
- Context. persistentstorecoordinator = PSC;
- // After running out, remember to [context release];
2. Add data to the database
- // Input context to create a person object
- Nsmanagedobject * person = [nsentitydescription insertnewobjectforentityforname: @ "person" inmanagedobjectcontext: Context];
- // Set simple attributes of person
- [Person setvalue: @ "mj" forkey: @ "name"];
- [Person setvalue: [nsnumber numberwithint: 27] forkey: @ "Age"];
- // Input context to create a card object
- Nsmanagedobject * card = [nsentitydescription insertnewobjectforentityforname: @ "card" inmanagedobjectcontext: Context];
- [Card setvalue: @ "4414241933432" forkey: @ "no"];
- // Set the relationship between person and card
- [Person setvalue: Card forkey: @ "card"];
- // Use the context object to synchronize data to the persistent Repository
- Nserror * error = nil;
- Bool success = [context save: & error];
- If (! Success ){
- [Nsexception raise: @ "database access error" Format: @ "% @", [error localizeddescription];
- }
- // 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
- // Initialize a query request
- Nsfetchrequest * request = [[nsfetchrequest alloc] init] autorelease];
- // Set the object to be queried
- Request. entity = [nsentitydescription entityforname: @ "person" inmanagedobjectcontext: Context];
- // Set sorting (by age in descending order)
- Nssortdescriptor * sort = [nssortdescriptor sortdescriptorwithkey: @ "Age" ascending: No];
- Request. sortdescriptors = [nsarray arraywithobject: Sort];
- // 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 *)
- Nspredicate * predicate = [nspredicate predicatewithformat: @ "name like % @", @ "* Itcast-1 *"];
- Request. predicate = predicate;
- // Execute the request
- Nserror * error = nil;
- Nsarray * objs = [context executefetchrequest: Request error: & error];
- If (error ){
- [Nsexception raise: @ "query error" Format: @ "% @", [error localizeddescription];
- }
- // Traverse data
- For (nsmanagedobject * OBJ in objs ){
- Nslog (@ "name = % @", [OBJ valueforkey: @ "name"]
- }
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
- // Input the object to be deleted
- [Context deleteobject: managedobject];
- // Synchronize the result to the database
- Nserror * error = nil;
- [Context save: & error];
- If (error ){
- [Nsexception raise: @ "delete error" Format: @ "% @", [error localizeddescription];
- }
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
- # Import <Foundation/Foundation. h>
- # Import <coredata/coredata. h>
- @ Class card;
- @ Interface person: nsmanagedobject
- @ Property (nonatomic, retain) nsstring * Name;
- @ Property (nonatomic, retain) nsnumber * age;
- @ Property (nonatomic, retain) card * card;
- @ End
Person. m
- # Import "person. H"
- @ Implementation person
- @ Dynamic name;
- @ Dynamic age;
- @ Dynamic card;
- @ End
Card. h
- # Import <Foundation/Foundation. h>
- # Import <coredata/coredata. h>
- @ Class person;
- @ Interface Card: nsmanagedobject
- @ Property (nonatomic, retain) nsstring * No;
- @ Property (nonatomic, retain) person * person;
- @ End
Card. m
- # Import "card. H"
- # Import "person. H"
- @ Implementation card
- @ Dynamic no;
- @ Dynamic person;
- @ End
When adding data to the database, you should write:
- Person * person = [nsentitydescription insertnewobjectforentityforname: @ "person" inmanagedobjectcontext: Context];
- Person. Name = @ "mj ";
- Person. Age = [nsnumber numberwithint: 27];
- Card * card = [nsentitydescription insertnewobjectforentityforname: @ "card" inmanagedobjectcontext: Context];
- Card. No = @ "4414245465656 ";
- Person. Card = card;
- // 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.