Some common Core Data usage and coredata usage

Source: Internet
Author: User

Some common Core Data usage and coredata usage

I. Introduction

Core Data is a pure object-oriented framework. It is essentially an ORM (Object Relational ing: Object Relational Mapping) that can operate SQLite databases in an object-oriented manner. In most cases, the underlying layer of Core Data adopts SQLite database as the persistent storage mode during actual development. It also allows data to be stored in the memory (data will be lost after the device is restarted), and data can be stored in other formats (such as XML ). To put it simply, it is a persistent tool used to operate entities and their associations.

2. Core Data Core concepts.

1. Entity

An object is a model object managed by Core Data. It is an instance of the NSManagedObject class or its subclass.

There are 1-1, 1-N, N-N associations between entities.

2. Entity description

NSEntityDescription: This object describes the specific information of an object (such as all attributes), which is equivalent to entity abstraction.

3. Managed Object Model

NSManagedObjectModel: This object is used to manage all entities and their associations.

4. Managed object context

NSManagedObjectContext: in short, all objects are under context management, and object addition, deletion, modification, and query operations must be completed through this object. Similar to Hibernate Session.

5. Persistent Storage Coordinator

NSPersistentStoreCoordinator: The underlying layer is connected with NSManagedObjectContext to manage the underlying storage format (such as SQLite database or XML ).

6. Capture requests

NSRetchRequest: This object encapsulates object query requests, such as the objects to be queried, query conditions (represented by NSPredicate), and sorting rules (all sorting rules defined by NSArray.

3. Use Core Data.

Note: If you select the "Use Core Data" check box when creating a project, Xcode automatically initializes all Core Data required resources. The first three steps are automatically completed, start step 1.

1. Import the CoreData. Framework for the project.

2. Add an object model file.

Xcode → File → New → File → Data Model → next → "object Model File name". xcdatamodeld → create;

3. Core API objects required for Core Data initialization. These are global objects and are generally operated in AppDelegate.

(1) Add three core attributes in AppDelegate. h and then add an execution storage method.

 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 (nonatomic, strong) NSManagedObjectContext *managedObjectContext; 9 @property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;10 @property (nonatomic, strong) NSPersistentStoreCoordinator *persistentStoreCoordinator;11 12 - (void)saveContext;13 14 @end

(2) initialize NSManagedObjectModel in AppDelegate. m.

1 - (NSManagedObjectModel *)managedObjectModel {3     if (_managedObjectModel != nil) {4         return _managedObjectModel;5     }6     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreData2" withExtension:@"momd"];7     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];8     return _managedObjectModel;9 }

(3) initialize NSPersistentStoreCoordinator in AppDelegate. m based on the NSManagedObjectModel object to set the underlying Data storage mode of Core Data.

 1 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 2     if (_persistentStoreCoordinator != nil) { 3         return _persistentStoreCoordinator; 4     } 5     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 6     NSURL *storeURL =  [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 7     storeURL = [storeURL URLByAppendingPathComponent:@"CoreData2.sqlite"]; 8     NSError *error = nil; 9     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {10         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);11         abort();12     }13     14     return _persistentStoreCoordinator;15 }                

(4) initialize NSManagedObjectContext in AppDelegate. m based on the NSManagedObjectModel object.

 1 - (NSManagedObjectContext *)managedObjectContext { 2     if (_managedObjectContext != nil) { 3         return _managedObjectContext; 4     } 5      6     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 7     if (!coordinator) { 8         return nil; 9     }10     _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];11     [_managedObjectContext setPersistentStoreCoordinator:coordinator];12     return _managedObjectContext;13 }

(5) Implement the saveContext method in AppDelegate. m to save data.

 1 - (void)saveContext { 2     NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 3     if (managedObjectContext != nil) { 4         NSError *error = nil; 5         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 6             NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 7             abort(); 8         } 9     }10 }

(6) implement this method in AppDelegate. m. When the application is terminated in the background, save the data in the context.

1 - (void)applicationWillTerminate:(UIApplication *)application {2     [self saveContext];3 }

After completing the above three steps, the Core Data project Initialization is complete. When the application needs to perform operations such as adding, deleting, modifying, and querying, you can directly call the managedObjectContext attribute in AppDelegate to perform the operation.

4. design the entity model.

Click "object model file name". xcdatamodeld file in the Xcode project navigation bar to open the object model and start editing.

(1) entity: it is the core object of the entity model. The entity must be an NSManagedObject class or its subclass. Click "Add Entity" to Add an object.

(2) request capturing: it is an NSFetchRequest object, which is usually created in code during actual development.

(3) configuration: default system configuration, no need to add it.

(4) Attribute: it is equivalent to the instance variable of the object. Select the generated object from the object list and click "Add Attribute" to Add the Attribute.

(5) Link: define the relationship between entities, such as 1-1, 1-N, and N-N. The procedure is as follows:

Select an object → click the plus sign under Relationships to add an association Relationship → enter the association name under Relationship → select the target object under Destination → select the association Type from the Type on the Xcode property panel → In Xcode select the cascade type in the Delete Rule on the property panel.

  • Relationship: the name of the association.
  • Destination: the target object of the association.
  • Inverse: establishes an association between the object and the target object to maintain data integrity. If this parameter is not set, the compiler generates a warning.
  • To One: 1-1.
  • Type: 1-N. // In the case of N-N, other entities need to be set for this entity to 1-N
  • Delete Rule's No Action: when the primary object is deleted, the associated target object remains unchanged.
  • Delete Rule's Nullify: when the primary object is deleted, the associated foreign key value of the target object is set to null.
  • Delete Rule's Cascade: when the primary object is deleted, the associated target object is also deleted Cascade.
  • Delete Rule's Deny: when the primary object is deleted, if the target object associated with the object still exists, the program rejects the operation to Delete the primary object. You must delete the target object to delete the primary object.

(6) Capture attributes: A filter condition can be executed when an associated object is obtained.

5. generate an object using an object model.

This is to generate a subclass of NSManagedObject based on an object in the object model file name. xcdatamodeld file.

Xcode → File → New → File → NSManagedObject Subclass → select object model File → select object in File (when there are more than 1 objects) → create;

6. add, delete, modify, and query data.

(1) Add an object.

  • Call the insertNewObjectForEntityForName: inManagedObjectContext: Class Method of NSEntityDescription to add a new object.
  • Set new object attributes.
  • Call the save method of the NSManagedObjectContext object to save the context.
    1 HLAuthor * author = [NSEntityDescription insertNewObjectForEntityForName: @ "HLAuthor" inManagedObjectContext: self. appDelegate. managedObjectContext]; 2 author. name = @ "Zhang San"; 3 author. authorDesc = @ "xxx"; 4 NSError * error = nil; 5 if (! [Self. appDelegate. managedObjectContext save: & error]) {6 NSLog (@ "failed to save: % @, % @", error, error. userInfo); 7}

(2) Delete an object.

  • Obtain the object to be deleted.
  • Call the nseobject of the NSManagedObjectContext object: Method to delete an object.
  • Call the save method of the NSManagedObjectContext object to save the context.
    1 HLAuthor * author = self. authorArray [indexPath. row]; 2 [self. appDelegate. managedObjectContext deleteObject: author]; 3 NSError * error = nil; 4 if (! [Self. appDelegate. managedObjectContext save: & error]) {5 NSLog (@ "deletion failed: % @, % @", error, error. userInfo); 6}

(3) Modify an object.

  • Obtain the object to be modified.
  • Modify Object Attributes.
  • Call the save method of the NSManagedObjectContext object to save the context.
    1 HLAuthor * author = .....; 2 author. name = .....; 3 author. authorDesc = .....; 4 NSError * error = nil; 5 if ([self. delegate. managedObjectContext save: & error]) {6 NSLog (@ "failed to modify: % @, % @", error, error. userInfo); 7}

(4) query entities.

  • Create an NSFetchRequest object.
  • Use the NSEntityDescription object to set the object to be crawled by the NSFetchRequest object.
  • Use the NSPredicate object to set filtering conditions (if needed), and use the NSSortDescriptor object to set sorting rules for query results (if needed ).
  • Call the executeFetchRequest: error of the NSManagedObjectcontext object to execute the query by using the method. All result sets that meet the conditions are returned.
    1 NSFetchRequest * request = [[NSFetchRequest alloc] init]; 2 NSEntityDescription * entity = [NSEntityDescription entityForName: @ "author" inManagedObjectContext: self. appDelegate. managedObjectContext]; 3 NSPredicate * predicate = [NSPredicate response: @ "nane = % @", @ "Zhang San"]; 4 NSSortDescriptor * descriptor = [NSSortDescriptor principal: @ "name" ascending: YES]; 5 request. entity = entity; 6 request. predicate = predicate; 7 request. sortDescriptors = @ [descriptor]; 8 NSError * error = nil; 9 NSArray * result = [self. appDelegate. managedObjectContext executeFetchRequest: request error: & error];

 

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.