Coredata first class understanding coredata, coredata first class understanding
Problem
There are many ways to persistently store data in iOS/Mac: NSUserDefault, Key chain, C language file interface, NSFileHandle, write method in basic framework, archive, and so on. In practical applications, we often need to convert the data into objects in a certain format, and perform certain filtering and other operations before using them, which is not very convenient. Apple provides us with a Core Data framework that allows us to operate Data directly in the form of objects, making these very simple.
Introduction
CoreData has several common elements:
Name |
Function |
NSManagedObjectModel |
Object Model, specifying the object files used |
NSPersistentStoreCoordinator |
Persistent Storage Coordinator, which sets the object storage mode and data storage location. |
NSManagedObjectContext |
Object Management Context, responsible for actual data operations (important) |
NSEntityDescriptor |
Object descriptor, which describes an object and can be used to generate objects corresponding to the object. |
NSManagedObject |
Object |
NSFetchRequest |
Object Query, equivalent to the Select statement of SQL |
Procedure
In this article, we use the simplest method, that is, when creating a project, check the "Core Data" option. Xcode automatically adds "NSManagedObjectModel", "NSPersistentStoreCoordinate", and "NSManagedObjectContext" to "AppDelegate" to facilitate subsequent use.
1. Create an "NSManagedObjectModel" object.
-(NSManagedObjectModel *) managedObjectModel {if (_ managedObjectModel! = Nil) {return _ managedObjectModel;} // CoreData model file path. Note that the compiled model file name extension is "momd" NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "CoreData01" withExtension: @ "momd"]; _ managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; return _ managedObjectModel ;}
2. Create the "NSPersistentStoreCoordinator" object.
-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {if (_ persistentStoreCoordinator! = Nil) {return _ persistentStoreCoordinator;} // specify the model object to be persisted _ persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] handler: [self managedObjectModel]; // persistent storage file NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent: @ "CoreData01.sqlite"]; NSError * error = nil; // set the storage format to SQLite if (! [_ PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: & error]) {} return _ persistentStoreCoordinator ;}
3. Create a context
-(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;} // create a management context _ managedObjectContext = [[NSManagedObjectContext alloc] init]; // associate the context with the storage object [_ managedObjectContext handler: coordinator]; return _ managedObjectContext ;}
4. Set the model file and add the Entity)
Click the "CoreData01.xcdatamodelId" file, add an object "Book", and add several attributes. The entity in Core Data is similar to the definition of a database table and specifies the names and types of different fields (attributes.
5. Create a model object class, "Editor> Create NSManagedobject Subclass ".
6. Select attributes that use scalar to define the value type (NSNumber is used by default to define attributes of the int, float, and Other types ).
7. Xcode automatically creates classes with the same object name and inherits from "NSManagedObject ".
8. create and store objects.
// Obtain the context object AppDelegate * AppDelegate = (appDelegate *) [UIApplication sharedApplication] created in AppDelegate. delegate; NSManagedObjectContext * context = appDelegate. managedObjectContext; // obtain the object descriptor NSEntityDescription * entity = [NSEntityDescription entityForName: @ "Book" Usage: context]; // create the object Book * book = [[NSManagedObject alloc] initWithEntity: entity insertIntoManagedObjectContext: context]; // set the Property book of the object. title = @ "Dream of Red Mansions"; // save the data [context save: nil];
9. You can use "NSFetchRequest" to retrieve data from the file later.
AppDelegate * appDelegate = (AppDelegate *) [UIApplication sharedApplication]. delegate; NSManagedObjectContext * context = appDelegate. managedObjectContext; // create a request object to obtain all the data corresponding to the object Book. You can set predicate and sortDescriptors for NSFetchRequest to filter and sort the results. NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName: @ "Book"]; NSArray * result = [context executeFetchRequest: fetchRequest error: nil]; NSLog (@ "% @", result );
Summary
The simple use of Core Data is still very convenient. We only need to focus on the Data content and processing logic, without the need to consider too many storage operations. However, it requires a lot of code that does not seem to be directly associated, making everyone feel very complicated.
This document consistsChangsha Davy EducationSort.