IOS development and ios development tutorial

Source: Internet
Author: User

IOS development and ios development tutorial
Core Data

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.

Traditional databases need to write Data to databases, and they need to write SQL statements Core Data to avoid the trouble of writing SQL statements.

How to Use CoreData

1. Creating a model file is equivalent to a database
2. Add an object equivalent table
3. Create an object class similar to the model class
4. Generate the contextual model file to generate a database
5. Save the object to the database
6. Get objects from the database
7. Update Data
8. delete data

1. Create a model file
The so-called model is to generate database tables indirectly.

2. Add an object

3. Create an object class
Take creating an employee entity class as an Example

Generate upstream and downstream file join model file generate Database
NSManagedObjectContext _ context = [[NSManagedObjectContext alloc] init]; // model file NSManagedObjectModel * model = [NSManagedObjectModel mergedModelFromBundles: nil]; // NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] Persistence: model]; NSString * doc = [persistence (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSLog (@ "% @", doc); NSString * sqlitePath = [doc stringByAppendingPathComponent: @ "company. sqlite "]; // data storage type database storage path [store addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: [NSURL fileURLWithPath: sqlitePath] options: nil error: nil]; _ context. persistentStoreCoordinator = store;
Save the object to the database
Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];    employee.name = @"zhangsan";    employee.age = @18;    employee.height = @1.89;    [_context save:nil];
Enable the SQL statement output of CoreData
1. Open Product, click EditScheme... 2. Click Arguments, and add 2 items 1>-com. apple. CoreData. SQLDebug 2> 1 to ArgumentsPassed On Launch.
CoreData instance generation entity class
#import <Foundation/Foundation.h>#import <CoreData/CoreData.h>@interface Employee : NSManagedObject@property (nonatomic, retain) NSString * name;@property (nonatomic, retain) NSNumber * age;@property (nonatomic, retain) NSNumber * height;@end
#import "Employee.h"@implementation Employee@dynamic name;@dynamic age;@dynamic height;@end

Import header file framework

#import "ViewController.h"#import <CoreData/CoreData.h>#import "Employee.h"@interface ViewController ()@property(strong,nonatomic)NSManagedObjectContext *context;@end
CoreData fuzzy query
@ Implementation ViewController # pragma mark fuzzy query-(IBAction) likeSearcher :( id) sender {// query NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Employee"]; // filter // 1. query NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name BEGINSWITH % @", @ "wang"]; // 2. end with si NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name ENDSWITH % @", @ "si"]; // 3. the name contains g NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name CONTAINS % @", @ "g"]; // 4. like ends with si NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name like % @", @ "li *"]; request. predicate = pre; // read information NSError * error = nil; NSArray * emps = [self. context executeFetchRequest: request error: & error]; if (! Error) {NSLog (@ "emps: % @", emps); for (Employee * emp in emps) {NSLog (@ "% @", emp. name, emp. age, emp. height) ;}} else {NSLog (@ "% @", error );}}
CoreData update data
# Pragma mark update employee information-(IBAction) updateEmployee :( id) sender {// change the height of wangwu to 1.7 // 1. find wangwu NSArray * emps = [self findEmployeeWithName: @ "wangwu"]; // 2. update height if (emps. count = 1) {Employee * emp = emps [0]; emp. height = @ 1.7;} // 3. synchronize (SAVE) data to [self. context save: nil];}-(NSArray *) findEmployeeWithName :( NSString *) name {// 1. search for Employee NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Employee"]; NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name = % @", name]; request. predicate = pre; return [self. context executeFetchRequest: request error: nil];}
CoreData delete data
# Pragma mark Delete employee-(IBAction) deleteEmployee :( id) sender {[self deleteEmployeeWithName: @ "lisi"];}-(void) deleteEmployeeWithName :( NSString *) name {// Delete zhangsan // 1. found zhangsan NSFetchRequest * request = [NSFetchRequest response: @ "Employee"]; NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name = % @", name]; request. predicate = pre; // 2. delete zhangsan NSArray * emps = [self. context executeFetchRequest: request error: nil]; for (Employee * emp in emps) {NSLog (@ "delete Employee % @", emp. name); [self. context deleteObject: emp];} // 3. synchronize the database with context // all operations are in the memory temporarily. Call save to synchronize the database [self. context save: nil];}
CoreData query data
# Pragma mark Read employee information-(IBAction) readEmployee :( id) sender {// create a request object (fill in the name of the table to be queried-entity class) NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @ "Employee"]; // filter the query results. // search for Michael and the height is greater than 1.8 NSPredicate * pre = [NSPredicate predicateWithFormat: @ "name = % @ AND height> % @", @ "zhangsan", @ (1.8)]; // request. predicate = pre; // sort by height in ascending order NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey: @ "he Ight "ascending: NO]; // request. sortDescriptors = @ [sort]; // query by page for a total of 13 Data Records. Each page displays 5 data records. // the data request on the first page. fetchLimit = 5; request. fetchOffset = 10; // read information NSError * error = nil; NSArray * emps = [self. context executeFetchRequest: request error: & error]; if (! Error) {NSLog (@ "emps: % @", emps); for (Employee * emp in emps) {NSLog (@ "% @", emp. name, emp. age, emp. height) ;}} else {NSLog (@ "% @", error) ;}# pragma mark add employee information-(IBAction) addEmployee :( id) sender {// create Employee * emp1 = [NSEntityDescription insertNewObjectForEntityForName: @ "Employee" inManagedObjectContext: self. context]; // set the employee attribute emp1.name = @ "lisi"; emp1.age = @ 28; emp1.height = @ 2.10; // save- Operate NSError * error = nil; [self. context save: & error]; if (! Error) {NSLog (@ "success");} else {NSLog (@ "% @", error );}}
CoreData creation Context
-(Void) setupContext {// 1. context Association Company. xcdatamodeld model file NSManagedObjectContext * context = [[NSManagedObjectContext alloc] init]; // associate the model file // create a model object // pass an nil to associate all the model files under the bundle with NSManagedObjectModel * model = [NSManagedObjectModel mergedModelFromBundles: nil]; // NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: model]; // name of the storage database NSError * error = nil; // obtain the docment directory NSString * doc = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // path to save the database NSString * sqlitePath = [doc stringByAppendingPathComponent: @ "company. sqlite "]; [store addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: [NSURL fileURLWithPath: sqlitePath] options: nil error: & error]; context. persistentStoreCo Ordinator = store; self. context = context;}-(void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {// create an employee for (int I = 0; I <10; I ++) {Employee * emp1 = [NSEntityDescription insertNewObjectForEntityForName: @ "Employee" inManagedObjectContext: self. context]; // set the employee attribute emp1.name = [NSString stringWithFormat: @ "wangwu % d", I]; emp1.age = @ (28 + I); emp1.height = @ 2.10; // save-operate NSError through context * Error = nil; [self. context save: & error]; if (! Error) {NSLog (@ "success");} else {NSLog (@ "% @", error) ;}}@ end
Call
-(Void) viewDidLoad {[super viewDidLoad]; // create a database company. sqlite // the database requires a table employee table (name, age, heimpaired) // Add employee information to the data // CoreData [self setupContext];}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

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.