Creation of the CoreData database

Source: Internet
Author: User

CoreData database Add, delete, change, check (show in TableView)

First, create a new Datamodel database table (Import CoreData Class)

Create a new nsmanagedobject, generate the Estudent class

  1. #import <Foundation/Foundation.h>

  2. #import <CoreData/CoreData.h>

  3. @class NSManagedObject;

  4. @interface EStudent : NSManagedObject

  5. @property (nonatomic, retain) NSNumber * age;

  6. @property (nonatomic, retain) NSNumber * height;

  7. @property (nonatomic, retain) NSString * name;

  8. @property (nonatomic, retain) NSManagedObject *school;

  9. @end

  10. #import "EStudent.h"

  11. //#import "NSManagedObject.h"

  12. #import <CoreData/CoreData.h>

  13. @implementation EStudent

  14. @dynamic age;

  15. @dynamic height;

  16. @dynamic name;

  17. @dynamic school;

  18. @end

Second, custom xib, set up and delete the search view

Note the delegate settings for TableView

Third, create the database

-(void) Preparecoredata

{

A. Creating a database-creating a model file

B. Creating a table-creating an entity

C. Building the entity class Model

D. Writing a code initialization framework

1. Create the Nsmanagedobjectmodel model class based on the model file

Nsurl * FileURL = [[NSBundle mainbundle] urlforresource:@ "Main" withextension:@ "MOMD"];

Nsmanagedobjectmodel * Managedobjectmodel = [[Nsmanagedobjectmodelalloc] initwithcontentsofurl:fileurl];

2. Associating model classes and database files

2.1 Creating a Persistence Coordinator

Nspersistentstorecoordinator * coordinator = [[Nspersistentstorecoordinator Alloc]initwithmanagedobjectmodel: Managedobjectmodel];

2.2 Specifying a persistence class for the Coordinator

NSString * DbPath = [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents/main.sqlite"];

NSLog (@ "Path:%@", DbPath);

Nserror * error = NIL;

[Coordinator AddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nil Url:[nsurl Fileurlwithpath:dbpath] options:nilerror:&error];

if (Error) {

NSLog (@ "%@", error);

}

3. Create Nsmanagedobjectcontext context

Self.context = [[Nsmanagedobjectcontext alloc] init];

Self.context.persistentStoreCoordinator = coordinator;

}

-(void) Initialdatasource

{

Self.datasource = [Nsmutablearray new];

Reading data

1. Create nsfetchrequest, fetch data request class

Nsfetchrequest * request = [[Nsfetchrequest alloc]initwithentityname:@ "Estudent"];

Nserror * error = NIL;

2. Fetching data from the current context

Nsarray * array = [Self.context executefetchrequest:requesterror:&error];

if (Error) {

NSLog (@ "%@", error);

Return

}

[Self.datasource Addobjectsfromarray:array];

}


Iv. Customizing the content of Tableviewcell

#pragma mark-tableview Delegate

-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section

{

return self.dataSource.count;

}

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexpath{

Mytableviewcell * cell = [tableviewdequeuereusablecellwithidentifier:@ "cell"];

if (!cell) {

cell = [[UITableViewCell alloc] initwithstyle:uitableviewcellstylesubtitle reuseidentifier:@ "Cell"];

cell = [[[NSBundle Mainbundle] loadnibnamed:@ "Mytableviewcell" owner:self Options:nil]firstobject];

}

Estudent * s = [Self.datasource objectAtIndex:indexPath.row];

Cell.textLabel.text = S.name;

Cell.detailTextLabel.text = [NSString stringwithformat:@ "%@", S.age];

Cell.nameTF.text = S.name;

Cell.heightTF.text = [NSString stringwithformat:@ "%@", s.height];

Cell.ageTF.text = [NSString stringwithformat:@ "%@", S.age];

return cell;

}

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath

{

return 90;

}

V. Increase and revise the operation of the check

??? Increase

Insert operation

1. Create an entity class from the Nsentitydescription class

Arg1. Entity name (table name, name of entity Class); arg2. Context

Estudent * s = [nsentitydescriptioninsertnewobjectforentityforname:@ "Estudent" InManagedObjectContext:self.context] ;

S.name = Self.nameTF.text;

S.age = [NSNumber numberWithInt:self.ageTF.text.intValue];

S.height = [NSNumbernumberWithFloat:self.heightTF.text.floatValue];

2. Deposit into the database

Nserror * error = NIL;

[Self.context save:&error];

[Self.datasource addobject:s];

[Self.tableview Reloaddata];

??? By deleting

Nsindexpath * Path = [Self.tableview Indexpathforselectedrow];

Delete

1. Find the object you want to delete

Estudent * student = [Self.datasource objectAtIndex:path.row];

2. Deleting an object from the context

[Self.context deleteobject:student];

3. Save context to File

[Self.context Save:nil];

[Self.datasource removeobject:student];

[Self.tableview Reloaddata];



??? Change

Change data

1. Find the object you want to modify

Nsindexpath * Path = [Self.tableview Indexpathforselectedrow];

Estudent * student = [Self.datasource objectAtIndex:path.row];

2. Modifications

Student.name = Self.nameTF.text;

3. Save

[Self.context Save:nil];

[Self.tableview Reloaddata];



??? Check

Inquire

1. Create a Query Request class

Nsfetchrequest * request = [[Nsfetchrequest alloc]initwithentityname:@ "Estudent"];

2. Set Filter Criteria

// =

CONTAINS

Beginswith

Endswithd

nspredicate * predicate = [nspredicate predicatewithformat:@ "name CONTAINS%@", Self.nameTF.text];

Request.predicate = predicate;

N.

Nserror * error = NIL;

Nsarray * array = [Self.context executefetchrequest:requesterror:&error];

if (Error) {

NSLog (@ "%@", error);

}

[Self.datasource removeallobjects];

[Self.datasource Addobjectsfromarray:array];

[Self.tableview Reloaddata];

Creation of the CoreData database

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.