IOS-Core Data basics and ios-coredata Basics

Source: Internet
Author: User

IOS-Core Data basics and ios-coredata Basics

Core Data basics

Core Data is an API set designed to simplify persistent storage of Data objects.

Here, we will not popularize the concept. First, we will use a simple case to feel the subtlety of Core Data.

Select Use Core Data when creating a project.

1 # import <UIKit/UIKit. h> 2 # import <CoreData/CoreData. h> 3 4 @ interface AppDelegate: UIResponder <UIApplicationDelegate> 5 6 @ property (strong, nonatomic) UIWindow * window; 7 8 @ property (readonly, strong, nonatomic) implements * managedObjectContext; 9 @ property (readonly, strong, nonatomic) NSManagedObjectModel * managedObjectModel; 10 @ property (readonly, strong, nonatomic) implements * persistentStoreCoordinator; 11 12-(void) saveContext; 13-(NSURL *) applicationDocumentsDirectory; 14 @ endAppDelegate. h 1 # import "AppDelegate. h "2 3 @ interface AppDelegate () 4 5 @ end 6 7 @ implementation AppDelegate 8 9 10-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {11 // Override point for customization after application launch. 12 return YES; 13} 14 15-(void) applicationWillResignActive :( UIApplication *) application {16 // Sent whe N 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. 17 // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. games shocould use this method t O pause the game. 18} 19 20-(void) applicationDidEnterBackground :( UIApplication *) application {21 // 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. 22 // If your application supports background execution, this method is called instead o F applicationWillTerminate: when the user quits. 23} 24 25-(void) applicationWillEnterForeground :( UIApplication *) application {26 // 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. 27} 28 29-(void) applicationDidBecomeActive :( UIApplication *) application {30 // Restart any tasks that were paused (Or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface. 31} 32 33-(void) applicationWillTerminate :( UIApplication *) application {34 // Called when the application is about to terminate. save data if appropriate. see also applicationDidEnterBackground :. 35 // Saves changes in the application's managed ob Ject context before the application terminates. 36 [self saveContext]; 37} 38 39 # pragma mark-Core Data stack 40 41 @ synthesize managedObjectContext = _ managedObjectContext; 42 @ synthesize managedObjectModel = _ managedObjectModel; 43 @ synthesize persistentStoreCoordinator = _ persistentStoreCoordinator; 44 45-(NSURL *) applicationDocumentsDirectory {46 // The directory the application uses Store the Core Data store file. this code uses a directory named "com. wyg. coreDataDemo "in the application's documents directory. 47 return [[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] lastObject]; 48} 49 50-(optional *) managedObjectModel {51 // 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. 52 if (_ managedObjectModel! = Nil) {53 return _ managedObjectModel; 54} 55 NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "CoreDataDemo" withExtension: @ "momd"]; 56 _ managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; 57 return _ managedObjectModel; 58} 59 60-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {61 // The persistent store coordinator for the application. this Implementation creates and return a coordinator, having added the store for the application to it. 62 if (_ persistentStoreCoordinator! = Nil) {63 return _ persistentStoreCoordinator; 64} 65 66 // Create the coordinator and store 67 68 _ persistentStoreCoordinator = [[using alloc] Using: [self managedObjectModel]; 69 NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent: @ "CoreDataDemo. sqlite "]; 70 NSError * error = nil; 71 NSString * failureReason = @" There was An error creating or loading the application's saved data. "; 72 if (! [_ PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: & error]) {73 // Report any error we got. 74 NSMutableDictionary * dict = [NSMutableDictionary dictionary]; 75 dict [NSLocalizedDescriptionKey] = @ "Failed to initialize the application's saved data"; 76 dict [partition] = failureReason; 77 dict [NSUnderlyingE RrorKey] = error; 78 error = [NSError errorWithDomain: @ "YOUR_ERROR_DOMAIN" code: 9999 userInfo: dict]; 79 // Replace this with code to handle the error appropriately. 80 // 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. 81 NSLog (@ "Unresolved error % @, % @", error, [error us ErInfo]); 82 abort (); 83} 84 85 return _ persistentStoreCoordinator; 86} 87 88 89-(NSManagedObjectContext *) managedObjectContext {90 // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application .) 91 if (_ managedObjectContext! = Nil) {92 return _ managedObjectContext; 93} 94 95 NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; 96 if (! Coordinator) {97 return nil; 98} 99 _ managedObjectContext = [[NSManagedObjectContext alloc] init]; 100 [_ managedObjectContext handler: coordinator]; 101 return _ managedObjectContext; 102} 103 104 # pragma mark-Core Data Saving support105 106-(void) saveContext {107 NSManagedObjectContext * managedObjectContext = self. managedObjectContext; 108 if (managedObjectContext! = Nil) {109 NSError * error = nil; 110 if ([managedObjectContext hasChanges] &! [ManagedObjectContext save: & error]) {111 // Replace this implementation with code to handle the error appropriately.112 // 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.113 NSLog (@ "Unresolved error % @, % @", error, [error userInfo]); 114 abort (); 115} 116} 117} 118 119 @ endAppDelegate. m

We may feel the initial contact is dense, so we don't need to worry about it for the moment. Since the system is automatically generated for us, we can use it directly.

Now, click the CoreDataDemo. xcdatamodeld file to view the following interface.

1 # import <Foundation/Foundation. h> 2 # import <CoreData/CoreData. h> 3 4 @ class People; 5 6 @ interface Book: NSManagedObject 7 8 @ property (nonatomic, retain) NSNumber * name; 9 @ property (nonatomic, retain) NSString * author; 10 @ property (nonatomic, retain) People * people; 11 12 @ endBook. h 1 # import "Book. h "2 # import" People. h "3 4 5 @ implementation Book 6 7 @ dynamic name; 8 @ dynamic author; 9 @ dynamic people; 10 11 @ endBook. m 1 # import <Foundation/Foundation. h> 2 # import <CoreData/CoreData. h> 3 4 5 @ interface People: NSManagedObject 6 7 @ property (nonatomic, retain) NSString * name; 8 @ property (nonatomic, retain) NSNumber * age; 9 @ property (nonatomic, retain) NSManagedObject * book; 10 11 @ endPeople. h 1 # import "People. h" 2 3 4 @ implementation People 5 6 @ dynamic name; 7 @ dynamic age; 8 @ dynamic book; 9 10 @ endPeople. m

So far, everything is ready, and only the code is missing.

Our operations on Core Data include adding, deleting, modifying, and querying the Code directly.

In the AppDelegate startup function, add the following code to add a record to Core Data:

1 // managed object context, somewhat similar to database 2 NSManagedObjectContext * context = self. managedObjectContext; 3 // instance, which is somewhat similar to a table. Insert a piece of data and assign 4 People * people = [NSEntityDescription insertNewObjectForEntityForName: @ "People" inManagedObjectContext: context] to the object attribute. 5 people. name = @ "wyg"; 6 7 Book * book = [NSEntityDescription insertNewObjectForEntityForName: @ "Book" inManagedObjectContext: context]; 8 book. name = @ "Romance of the Three Kingdoms"; 9 10 people. book = book; 11 12 [self saveContext];Add 1 NSManagedObjectContext * context = self. managedObjectContext; 2 NSEntityDescription * entity = [NSEntityDescription entityForName: @ "People" inManagedObjectContext: context]; 3 NSFetchRequest * request = [NSFetchRequest new]; 4 request. entity = entity; 5 NSArray * arr = [context executeFetchRequest: request error: nil]; 6 7 for (People * object in arr) 8 {9 NSLog (@ "% @, % @ ", object. name, object. book. name); 10}Query

Result:

Key components of Core Data: data store, Persistent Store Coordinator, Managed Object model ), managed Object Context (Managed Object Context), which may be difficult to understand and irrelevant. We will gradually understand these terms in future. 1. Data Storage: data storage is one or more files that store data. When a message is sent to Core Data, it is actually written to a disk file. Data storage creation depends on the parameters used to create data storage. Data storage can be a binary file, an SQLite database, or a data file in the memory. 2. Persistent Storage Coordinator: the persistent Storage Coordinator is an instance of NSPersistentStoreCoordinator and plays an intermediate role in context and data storage. The Coordinator obtains data requests from the context and forwards them to appropriate data storage. 3. Managed object model: an instance of NSManagedObjectModel. The model is a group of entities that define data objects in applications. 4. Managed object context: NSManagedObjectContext instance, used to save all managed data objects. You can think of the context as a sandbox for saving all application data. You can add, delete, and modify objects in the context.

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.