Getting Started with Core data

Source: Internet
Author: User
Tags sqlite database

Getting started with Core dataTags: Core dataiosiosios data Access database data persistence Brief 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.

The model files are in core data, the objects that need to be mapped are called entities (entity), and the model files of core data are 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.

About Nsmanagedobject

1. 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)


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 perform crud operations

Code implementation first add Coredata.framework and import the main header file <CoreData/CoreData.h>


1. Setting up the context
[Java]View Plaincopy
  1. To load a model file from an application package
  2. Nsmanagedobjectmodel *model = [Nsmanagedobjectmodel Mergedmodelfrombundles:nil];
  3. Incoming model object, initializing Nspersistentstorecoordinator
  4. Nspersistentstorecoordinator *PSC = [[[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:model] Autorelease];
  5. To build the path to 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, where SQLite is used as the repository
  9. Nserror *error = nil;
  10. Nspersistentstore *store = [PSC addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:url Options:nil error:&error];
  11. if (store = = nil) { //Direct Throw exception
  12. [NSException raise:@"Add Database Error" format:@"%@", [Error localizeddescription]];
  13. }
  14. Initialize context, set Persistentstorecoordinator property
  15. Nsmanagedobjectcontext *context = [[Nsmanagedobjectcontext alloc] init];
  16. Context.persistentstorecoordinator = PSC;
  17. After use, remember to [context release];

2. Adding data to the database
[Java]View Plaincopy
  1. Incoming context, creating a person entity object
  2. Nsmanagedobject *person = [nsentitydescription insertnewobjectforentityforname:@"Person" inmanagedobjectcontext  : Context];
  3. Set simple properties for person
  4. [Person setvalue:@"MJ" forkey:@"name"];
  5. [Person Setvalue:[nsnumber numberwithint:] forkey:@' age ';
  6. Incoming context, creating a card entity object
  7. Nsmanagedobject *card = [nsentitydescription insertnewobjectforentityforname:@"card" Inmanagedobjectcontext:  Context];
  8. [Card setvalue:@"4414241933432" forkey:@"no"];
  9. Set the association between person and card
  10. [Person Setvalue:card forkey:@"card"];
  11. Use context objects to synchronize data to a persistent repository
  12. Nserror *error = nil;
  13. BOOL success = [Context save:&error];
  14. if (!success) {
  15. [NSException raise:@"Access database error" format:@"%@", [Error localizeddescription]];
  16. }
  17. 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
[Java]View Plaincopy
  1. Initializing a query Request
  2. Nsfetchrequest *request = [[[[Nsfetchrequest alloc] init] autorelease];
  3. Set the entity to query
  4. request.entity = [nsentitydescription entityforname:@"person" inmanagedobjectcontext:context];
  5. Set sort (by age descending)
  6. Nssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@"age" ascending:no];
  7. Request.sortdescriptors = [Nsarray arraywithobject:sort];
  8. 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*)
  9. Nspredicate *predicate = [nspredicate predicatewithformat:@"name like%@", @"*itcast-1*"];
  10. Request.predicate = predicate;
  11. Execute 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. Traversing data
  18. For (Nsmanagedobject *obj in Objs) {
  19. NSLog (@"name=%@", [obj valueforkey:@"name"]
  20. }
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
[Java]View Plaincopy
    1. Incoming entity objects that need to be deleted
    2. [Context Deleteobject:managedobject];
    3. Synchronizing the results to the database
    4. Nserror *error = nil;
    5. [Context save:&error];
    6. if (Error) {
    7. [NSException raise:@"Delete error" format:@"%@", [Error localizeddescription]];
    8. }

Open the CoreData SQL statement output Switch 1. Open product, click Editscheme ...
2. Click arguments to add 2 items to argumentspassed on launch
1>-com.apple.coredata.sqldebug
2> 1



Create a subclass of Nsmanagedobject by 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
[Java]View Plaincopy
    1. #import <foundation/foundation.h>   
    2. #IMPORT&NBSP;<COREDATA/COREDATA.H>&NBSP;&NBSP;
    3. &NBSP;&NBSP;
    4. @class  card;  
    5. Li class= "alt" >&NBSP;&NBSP;
    6. @interface  person : nsmanagedobject   
    7.   
    8. @property   ( Nonatomic, retain)  nsstring * name;  
    9. @property   (nonatomic, retain)  nsnumber * age;  
    10. @property   (nonatomic, retain)  card *card;  
    11. &NBSP;&NBSP;
    12. @end   

Person.m
[Java]View Plaincopy
    1. #Import "Person.h"
    2. @implementation person
    3. @dynamic name;
    4. @dynamic age;
    5. @dynamic Card;
    6. @end

Card.h
[Java]View Plaincopy
    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
[Java]View Plaincopy
    1. #Import "Card.h"
    2. #Import "Person.h"
    3. @implementation Card
    4. @dynamic No;
    5. @dynamic person;
    6. @end

So when you add data to the database, you should write:
[Java]View Plaincopy
    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. 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

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.