Core Data for IOS Data storage, ioscore

Source: Internet
Author: User

Core Data for IOS Data storage, ioscore

Core Date is a Data Persistence Solution Introduced after ios3.0. It is officially recommended by Apple and does not require third-party frameworks. Core Date is actually an encapsulation of SQLite and provides a more advanced persistence mode. When operating a database, you do not need to use SQL statements, which means you can operate data in the database even if you do not understand SQL statements.

When you use database operations in various application development, you often use (ORM) "object relationship ing". Core Data is such a mode. ORM converts a table in a relational database into an object in a program, but it actually operates on the data in the data.

You do not need to manually create a database when using Core Data for database access. The database creation process is completely completed by the Core Data framework automatically. What developers need to do is to create a model, you do not need to worry about creating a specific database. Simply put, Core Data encapsulates operations such as database creation, table creation, object and table conversion, greatly simplifying our operations.

Compared with SQLite, the Core Date is more primitive and complex. The C function is used to operate the database, but SQLite is more controllable and can be used across platforms.

Next, let's take a look at the simple use of Core Data.

1. Use Core Data to add entities and Models

You can choose to use Core Data when creating a project. After the project is successfully created, the relevant code is automatically added to the AppDelegate class. In addition, a Data model file JRCoreData. xcdatamodeld is automatically generated.

 

AppDelegate. h

// AppDelegate. h // JRCoreData /// Created by jerei on 15-6-24. // Copyright (c) 2015 jerehedu. all rights reserved. // # import <UIKit/UIKit. h> # import <CoreData/CoreData. h> @ interface AppDelegate: UIResponder <UIApplicationDelegate> @ property (strong, nonatomic) UIWindow * window; @ property (readonly, strong, nonatomic) implements * managedObjectContext; @ property (readonly, strong, nonatomic) implements * managedObjectModel; @ property (readonly, strong, nonatomic) implements * persistentStoreCoordinator;-(void) saveContext;-(NSURL *) applicationDocumentsDirectory; @ end

AppDelegate. m

// AppDelegate. m // JRCoreData /// Created by jerei on 15-6-24. // Copyright (c) 2015 jerehedu. all rights reserved. // # import "AppDelegate. h "@ interface AppDelegate () @ end @ implementation AppDelegate-(BOOL) application :( UIApplication *) application metadata :( NSDictionary *) launchOptions {// Override point for customization after application launch. return YES;}-(void) applicationW IllResignActive :( UIApplication *) application {// Sent when the application is about to move from active to inactive state. this can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle dow N OpenGL ES frame rates. games shocould use this method to pause the game .} -(void) applicationDidEnterBackground :( UIApplication *) application {// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background exec Ution, this method is called instead of applicationWillTerminate: when the user quits .} -(void) applicationWillEnterForeground :( UIApplication *) application {// Called as part of the transition from the background to the inactive state; here you can undo records of the changes made on entering the background .} -(void) applicationDidBecomeActive :( UIApplication *) application {// Restart any tasks that w Ere paused (or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface .} -(void) applicationWillTerminate :( UIApplication *) application {// Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :. // Saves changes in the application's managed object co Ntext before the application terminates. [self saveContext] ;}# pragma mark-Core Data stack @ synthesize managedObjectContext = _ managedObjectContext; @ synthesize constraint = _ managedObjectModel; @ synthesize constraint = _ ignore;-(NSURL *) applicationDocumentsDirectory {// The directory the application uses to store the Core Data store file. this code uses A directory named "com. jerehedu. JRCoreData "in the application's documents directory. return [[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] lastObject];}-(NSManagedObjectModel *) managedObjectModel {// The managed object model for the application. it is a fatal error for the application not to be able to find and load its model. if (_ managedObje CtModel! = Nil) {return _ managedObjectModel;} NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "JRCoreData" withExtension: @ "momd"]; _ managedObjectModel = [[delealloc] initWithContentsOfURL: modelURL]; return _ managedObjectModel;}-(optional *) persistentStoreCoordinator {// The persistent store coordinator for the application. this implementation creates and ret Urn a coordinator, having added the store for the application to it. if (_ persistentStoreCoordinator! = Nil) {return _ persistentStoreCoordinator;} // Create the coordinator and store _ persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] handler: [self managedObjectModel]; NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent: @ "JRCoreData. sqlite "]; NSError * error = nil; NSString * failureReason = @" There was an error creating or loading The application's saved data. "; if (! [_ PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: & error]) {// Report any error we got. NSMutableDictionary * dict = [NSMutableDictionary dictionary]; dict [region] = @ "Failed to initialize the application's saved data"; dict [region] = failureReason; dict [region] = erro R; error = [NSError errorWithDomain: @ "YOUR_ERROR_DOMAIN" code: 9999 userInfo: dict]; // Replace this with code to handle the error appropriately. // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. NSLog (@ "Unresolved error % @, % @", error, [error userInfo]); abort ();} return _ PersistentStoreCoordinator;}-(NSManagedObjectContext *) managedObjectContext {// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application .) if (_ managedObjectContext! = Nil) {return _ managedObjectContext;} NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; if (! Coordinator) {return nil;} _ managedObjectContext = [[NSManagedObjectContext alloc] init]; [_ managedObjectContext handler: coordinator]; return _ managedObjectContext ;} # pragma mark-Core Data Saving support-(void) saveContext {NSManagedObjectContext * managedObjectContext = self. managedObjectContext; if (managedObjectContext! = Nil) {NSError * error = nil; if ([managedObjectContext hasChanges] &! [ManagedObjectContext save: & error]) {// Replace this implementation with code to handle the error appropriately. // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. NSLog (@ "Unresolved error % @, % @", error, [error userInfo]); abort () ;}}@ end

If you do not select to use Core Data when creating a project, but need to use it later, you need to manually add the relevant code in AppDelegate. In addition, you must manually add a Data Model file.

 

When creating a Data Model file, note that the file name must match the file name mentioned in the managedObjectModel method in AppDelegate. m.

With the Data Model file, you can add entities and relationships to it. In fact, you can add tables to the database and create associations between tables. Add entity:

 

Each student has a class, and each class has multiple students. Therefore, the relationship between the students and the class can be established. Link creation:

 

After the relationship is established, you can switch the display style to view the relationship between entities in the form of charts ,:

 

After the above steps are completed, the table creation in the database has been completed. Compared with using SQLite, the SQL statements and the steps for Calling C functions to operate the database are omitted. In addition, you do not need to set a primary key when creating an object. The attribute type of the object is OC, and other object types in the object are added by establishing a link.

After creating an object, you can add the NSManagedObject subclass file. The system can automatically add the data model class corresponding to the object ,:

 

2. database operations through code

  1,Insert a data entry into the student table

When using Core Data, the NSManagedObjectContext object is added to AppDelegate. You need to obtain the context of the management object for operations. During the operation, you need to obtain the NSManagedObject object, set the object attribute value through kvc, and then call the save method to save the data through context.

-(Void) insert {AppDelegate * delegate = [[UIApplication sharedApplication] delegate]; // 1. obtain context NSManagedObjectContext * context = delegate. managedObjectContext; // 2. locate the object structure and generate an object/* NSEntityDescription Entity description, that is, table structure parameter 1: Table name parameter 2: who manages the instantiated object, is context */NSManagedObject * stu = [NSEntityDescription failed: @ "Student" inManagedObjectContext: context]; NSManagedObject * class1 = [NSEntityDescription failed: @ "Classes" failed: context]; [class1 setValue: [NSNumber numberWithInt: 1] forKey: @ "c_id"]; [class1 setValue: @ "Class 1" forKey: @ "c_name"]; // 3. set the object property value [stu setValue: [NSNumber numberWithInt: 1] forKey: @ "s_id"]; [stu setValue: @ "jerehedu" forKey: @ "s_name"]; [stu setValue: class1 forKey: @ "s_class"]; // 4. call context to save the object. if the object fails, the NSError * error is returned. if ([context save: & error]) {NSLog (@ "save OK ");} else {NSLog (@ "% @", error );}}

2. query all data in the student table

  The query operation is similar to the insert data operation, but the process of constructing the query object is added. The result set obtained by the query is an array. You can retrieve the query data by traversing the array.

-(Void) selectAll {AppDelegate * delegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext * context = delegate. managedObjectContext; NSEntityDescription * stu = [NSEntityDescription entityForName: @ "Student" failed: context]; // construct the query object NSFetchRequest * request = [[NSFetchRequest alloc] init]; [request setEntity: stu]; // executes the query. The returned result set NSArray * resultAry = [context executeFetchRequest: request error: nil]; // traverses the result set for (NSManagedObject * enity in resultAry) {NSLog (@ "id = % I name = % @ class = % @", [[enity valueForKey: @ "s_id"] intValue], [enity valueForKey: @ "s_name"], [[enity valueForKey: @ "s_class"] valueForKey: @ "c_name"]) ;}}

  3. query and update the student information of a specified condition.

In addition to constructing a query object, the query condition must be expressed by a predicate. Then, traverse the data in the query result array, modify the rows, and save the rows.

-(Void) update {// update (locate from database --> update) AppDelegate * delegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext * context = delegate. managedObjectContext; NSEntityDescription * stu = [NSEntityDescription entityForName: @ "Student" failed: context]; NSFetchRequest * request = [NSFetchRequest new]; [request setEntity: stu]; // construct a query condition, equivalent to the where clause NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "s_id = % I", 1]; // put the query condition in [request setPredicate: predicate]; // execute the query NSArray * studentAry = [context executeFetchRequest: request error: nil]; if (studentAry. count> 0) {// update the value NSManagedObject * obj = studentAry [0]; [obj setValue: @ "apple" forKey: @ "s_name"];} [context save: nil]; // display [self selectAll];}

  4. Delete student information under specified conditions

Before deletion, you must first query the data according to the conditions, delete the data, and save the data.

-(Void) delete {// delete first, and then delete AppDelegate * delegate = [[UIApplication sharedApplication] delegate]; NSManagedObjectContext * context = delegate. managedObjectContext; NSEntityDescription * stu = [NSEntityDescription entityForName: @ "Student" failed: context]; NSFetchRequest * request = [NSFetchRequest new]; [request setEntity: stu]; // construct a query condition, equivalent to the where clause NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "s_id = % I", 1]; // put the query condition in [request setPredicate: predicate]; // execute the NSManagedObject * obj = [[context executeFetchRequest: request error: nil] lastObject]; // Delete if (obj) {[context deleteObject: obj]; [context save: nil];} [self selectAll];}
Iii. Summary

Core Data is a Data persistence method officially recommended by Apple. during use, you do not need to import the database framework or use SQL statements to operate the database, the object model is used to operate databases based on the object-oriented idea. During usage, you must note that if the model changes, you can choose to re-generate the object file, but the automatically generated database will not be automatically updated. You need to consider re-generating the database, and port the data in the database. Core Data can simplify operations, but it does not support cross-platform use. If you want to implement cross-platform, you need to use SQLite for Data persistence.

 

For questions or technical exchanges, please join the official QQ group: (452379712)

 

Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
The copyright of this article belongs to Yantai Jerry Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the author's consent and provide the original article connection on the article page, otherwise, you are entitled to pursue legal liability.

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.