directory of this document
- First, Introduction
- Ii. model Files
- Third, understand the Nsmanagedobject object
- Iv. core objects in the CoreData
- Five, code implementation
- VI. opening the CoreData SQL statement output switch
- Vii. creating sub-classes of Nsmanagedobject
Back to Top
First, Introduction
Core data is a framework that appears after IOS5, which provides object-relational mapping (ORM) functionality that enables you to convert OC objects into data, store them in SQLite database files, and restore data saved in a database to OC objects. During this data operation, we do not need to write any SQL statements, which is somewhat similar to the famous Hibernate persistence framework, but the feature is definitely not hibernate powerful. Simply use the description to describe its function:
On the left is the relational model, that is, the database, the database has a person table, the person table contains ID, name, age three fields, and there are 2 records;
On the right is the object model, you can see that there are 2 OC objects;
With the core data framework, we can easily convert 2 of records in a database into 2 OC objects, or you can easily save 2 OC objects into a database, become 2 table records, and not write an SQL statement.
Back to Top
Ii. Model FilesIn core data, the object that needs to be mapped is called entity, and the model file of core data is used to describe all the entity and entity attributes in the app. Here is an example of a person (people) and a card (identity card) 2 entities, first look at the relationship between entity attributes and entities:
The person entity has: name, age, card (ID) three attributes
The card entity has: no (number), person (people) two attributes
Next look at the process of creating the model file:
1. Select a template
2. Adding entities
3. Add 2 basic attributes for person
4. Add the 1 Basic properties of a card
5. Establish the relationship between card and person
The figure in the right indicates that there is a person attribute in the card that has the type of man, the purpose of which is to set up a one-to-two relationship between a card and someone (which is recommended), and after adding the inverse attribute You will find that the inverse attribute in the card is also automatically mended.
Back to Top
Third, understand the Nsmanagedobject object1. Objects fetched from the database via core data are Nsmanagedobject objects by default
The 2.NSManagedObject mode of operation is somewhat similar to the Nsdictionary object, which accesses all entity properties via key-value pairs.
1> Setvalue:forkey: Store attribute value (property name is key)
2> Valueforkey: Get Property Value (property name is key)
Back to Top
Iv. Core objects in the CoreData
Note: Black denotes the class name, and red indicates a property within the class
Summary of development steps:
1. Initialize the Nsmanagedobjectmodel object, load the model file, and read all the entity information in the app
2. Initialize Nspersistentstorecoordinator object, add Persistence library (take SQLite database here)
3. Initialize the Nsmanagedobjectcontext object, get the context object operation entity, and make crud operations back to the top
Five, code implementationAdd coredata.framework and import primary header files first <CoreData/CoreData.h>
1. Setting up the context
- To load a model file from an application package
- Nsmanagedobjectmodel *model = [Nsmanagedobjectmodel Mergedmodelfrombundles:nil];
- Incoming model object, initializing Nspersistentstorecoordinator
- Nspersistentstorecoordinator *PSC = [[[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model] Autorelease];
- To build the path to the SQLite database file
- NSString *docs = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) lastObject];
- Nsurl *url = [Nsurl fileurlwithpath:[docs stringbyappendingpathcomponent:@"Person.data"]];
- Add a persistent repository, where SQLite is used as the repository
- Nserror *error = nil;
- Nspersistentstore *store = [PSC addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:url Options:nil error:&error];
- if (store = = nil) { //Direct Throw exception
- [NSException raise:@"Add Database Error" format:@"%@", [Error localizeddescription]];
- }
- Initialize context, set Persistentstorecoordinator property
- Nsmanagedobjectcontext *context = [[Nsmanagedobjectcontext alloc] init];
- Context.persistentstorecoordinator = PSC;
- After use, remember to [context release];
2. Adding data to the database
- Incoming context, creating a person entity object
- Nsmanagedobject *person = [nsentitydescription insertnewobjectforentityforname:@"Person" inmanagedobjectcontext : Context];
- Set simple properties for person
- [Person setvalue:@"MJ" forkey:@"name"];
- [Person Setvalue:[nsnumber numberwithint:] forkey:@' age ';
- Incoming context, creating a card entity object
- Nsmanagedobject *card = [nsentitydescription insertnewobjectforentityforname:@"card" Inmanagedobjectcontext: Context];
- [Card setvalue:@"4414241933432" forkey:@"no"];
- Set the association between person and card
- [Person Setvalue:card forkey:@"card"];
- Use context objects to synchronize data to a persistent repository
- Nserror *error = nil;
- BOOL success = [Context save:&error];
- if (!success) {
- [NSException raise:@"Access database error" format:@"%@", [Error localizeddescription]];
- }
- If you want to do an update: When you change the properties of an entity object and call [context Save:&error], you can synchronize the changed data to the database
3. Querying data from the database
- Initializing a query Request
- Nsfetchrequest *request = [[[[Nsfetchrequest alloc] init] autorelease];
- Set the entity to query
- request.entity = [nsentitydescription entityforname:@"person" inmanagedobjectcontext:context];
- Set sort (by age descending)
- Nssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@"age" ascending:no];
- Request.sortdescriptors = [Nsarray arraywithobject:sort];
- Set conditional filtering (search for records containing the string "Itcast-1" in name, note: When setting conditional filtering,% in a database SQL statement is replaced with *, so%itcast-1% should be written as *itcast-1*)
- Nspredicate *predicate = [nspredicate predicatewithformat:@"name like%@", @"*itcast-1*"];
- Request.predicate = predicate;
- Execute request
- Nserror *error = nil;
- Nsarray *OBJS = [Context executefetchrequest:request error:&error];
- if (Error) {
- [NSException raise:@"Query Error" format:@"%@", [Error localizeddescription]];
- }
- Traversing data
- For (Nsmanagedobject *obj in Objs) {
- NSLog (@"name=%@", [obj valueforkey:@"name"]
- }
Note: Core data does not immediately obtain the corresponding associated object based on the association relationship in the entity, such as when the person entity is fetched through Core data, and the associated card entity is not immediately queried, and the database is queried again when the application really needs to use the card. Loads the information for the card entity. This is the deferred loading mechanism for core data.
4. Deleting data from a database
- Incoming entity objects that need to be deleted
- [Context Deleteobject:managedobject];
- Synchronizing the results to the database
- Nserror *error = nil;
- [Context save:&error];
- if (Error) {
- [NSException raise:@"Delete error" format:@"%@", [Error localizeddescription]];
- }
Back to Top
vi. opening the CoreData SQL statement output switch1. Open product, click Editscheme ...
2. Click arguments to add 2 items to argumentspassed on launch
1>-com.apple.coredata.sqldebug
2> 1
Back to Top
Vii. Creating sub-classes of NsmanagedobjectBy default, entities taken with core data are of type Nsmanagedobject and can access data using key-value pairs. However, in general, entities may need to add some business methods to accomplish some other tasks on the basis of accessing the data, then they must create nsmanagedobject subclasses
Select Model File
Select the entity you want to create a subclass of
After creation, there are 2 more sub-classes
File content display:
Person.h
- #import <foundation/foundation.h>
- #IMPORT&NBSP;<COREDATA/COREDATA.H>&NBSP;&NBSP;
- &NBSP;&NBSP;
- @class card;
Li class= "alt" >&NBSP;&NBSP;
- @interface person : nsmanagedobject
-
- @property ( Nonatomic, retain) nsstring * name;
- @property (nonatomic, retain) nsnumber * age;
- @property (nonatomic, retain) card *card;
- &NBSP;&NBSP;
- @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
So when you add 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;
- Finally call [context save&error]; to save data
Here, the entire core data framework is the end of the introduction, in fact, core data is far more than these features, it also supports automatic revocation mechanism, one-to-many associations, etc., here does not introduce
Getting Started with Core data