Mantle makes it easy to write a simple model layer for your Cocoa or Cocoa Touch application. Mantle can still be a convenient translation layer between the API and your managed model objects.
This article uses mantle as a data model and uses it to create a data persistence process for the coredata interface.
The operation process is simple, that is, data conversion:
1. Manle data model
The method used for persistence in Mantle:
// A MTLModel object that supports being serialized to and from Core Data as
// NSManagedObject.
- @ Protocol MTLManagedObjectSerializing
- @ Required
// The name of the Core Data entity that the specified er serializes to and
// Deserializes from.
- + (NSString *) managedObjectEntityName;
// Specifies how to map property keys to different keys on the specified er's
// + ManagedObjectEntity.
- + (NSDictionary *) managedObjectKeysByPropertyKey;
. H file
[Objc]View plaincopyprint?
- # Import
-
- @ Interface BannerWrapper: MTLModel
-
- @ Property (nonatomic, readonly) bool result;
- @ Property (copy, nonatomic, readonly) NSNumber * resultId;
- @ Property (copy, nonatomic, readonly) NSString * resultMsg;
- @ Property (copy, nonatomic) NSArray * bannerList;
- + (NSSortDescriptor *) sortDescriptor;
- @ End
-
- @ Interface Banner: MTLModel
-
- @ Property (copy, nonatomic, readonly) NSNumber * bannerId;
- @ Property (copy, nonatomic, readonly) NSString * picUrl;
- @ Property (copy, nonatomic, readonly) NSString * toDetailUrl;
- @ Property (copy, nonatomic, readonly) NSNumber * width;
- @ Property (copy, nonatomic, readonly) NSNumber * height;
-
- @ End
. M file
[Objc]View plaincopyprint?
- # Import "Banner. h"
-
- @ Implementation BannerWrapper
-
- # Pragma mark-JSON serialization
-
- + (NSDictionary *) JSONKeyPathsByPropertyKey {
- Return @{
- @ "Result": @ "result ",
- @ "ResultId": @ "resultId ",
- @ "ResultMsg": @ "resultMSG ",
- @ "BannerList": @ "banner"
- };
- }
-
- + (NSValueTransformer *) bannerListJSONTransformer
- {
- Return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass: [Banner class];
- }
-
- # Pragma mark-Managed object serialization
-
- + (NSString *) managedObjectEntityName {
- Return @ "BannerWrapper ";
- }
-
- + (NSDictionary *) managedObjectKeysByPropertyKey {
- Return nil;
- }
-
- + (NSDictionary *) relationshipModelClassesByPropertyKey {
- Return @{
- @ "BannerList": [Banner class],
- };
- }
-
- // Data sorting method when retrieving data from coredata
- + (NSSortDescriptor *) sortDescriptor {
- Return [[NSSortDescriptor alloc] initWithKey: @ "resultId" ascending: YES];
- }
-
- @ End
-
- @ Implementation Banner
-
- # Pragma mark-JSON serialization
-
- + (NSDictionary *) JSONKeyPathsByPropertyKey {
- Return @{
- @ "BannerId": @ "id ",
- @ "PicUrl": @ "picUrl ",
- @ "ToDetailUrl": @ "toDetailUrl ",
- @ "Width": @ "width ",
- @ "Height": @ "height"
- };
- }
-
- # Pragma mark-Managed object serialization
-
- + (NSString *) managedObjectEntityName {
- Return @ "Banner ";
- }
-
- + (NSDictionary *) managedObjectKeysByPropertyKey {
- Return nil;
- }
-
- @ End
2. coredata persistence class
Brief Introduction to main elements of Coredata
There are a lot of pictures on the Internet, but I still think this picture on a book is the best:
- 1. Managed Object Model
The Managed Object Model is a data Model that describes an application. This Model contains entities, properties, and Fetch requests. (English terms are used below .)
2, Managed Object Context
Managed Object Context participates in the whole process of various operations on the data Object, and monitors the changes of the data Object to provide support for undo/redo and update the UI bound to the data.
3. Persistent Store Coordinator
Persistent Store Coordinator is equivalent to the data file manager, which processes the underlying reading and writing of data files. Generally, we do not need to deal with it.
4. Managed Object
The Managed Object data Object, which is associated with the Managed Object Context.
5, Controller
In the figure, the green controllers include Array Controller, Object Controller, and Tree Controller. These controllers are usually bound to Managed Object Context through control + drag, so that we can operate data visually in nib.
. H file
[Objc]View plaincopyprint?
- # Import
-
- @ Interface Persistence: NSObject
-
- // Data model object
- @ Property (strong, nonatomic) NSManagedObjectModel * managedObjectModel;
- // Context object
- @ Property (strong, nonatomic) NSManagedObjectContext * managedObjectContext;
- // Persistent storage Zone
- @ Property (strong, nonatomic) NSPersistentStoreCoordinator * persistentStoreCoordinator;
-
- // Determine the sqlite file storage path
- -(NSURL *) storeURL;
-
- // Initialize the database used by Core Data
- -(NSPersistentStoreCoordinator *) persistentStoreCoordinator;
-
- // Initialize the value assignment function of managedObjectModel
- -(NSManagedObjectModel *) managedObjectModel;
-
- // The initialization value assignment function of managedObjectContext
- -(NSManagedObjectContext *) managedObjectContext;
-
- // Save the MTLModel object to coredata
- -(BOOL) saveMTLModel :( MTLModel *) MtlModel
- Error :( NSError * _ autoreleasing *) error;
-
- // Extract MTLModel from coredata
- -(MTLModel *) getMTLmodel :( MTLModel *) MtlModel
- Error :( NSError * _ autoreleasing *) error;
-
- // + (NSFetchRequest *) fetchRequest;
- @ End
. M file
[Objc]View plaincopyprint?
- # Import "Persistence. h"
-
- @ Implementation Persistence
-
- @ Synthesize managedObjectContext;
- @ Synthesize managedObjectModel;
- @ Synthesize persistentStoreCoordinator;
-
-
- // Determine the sqlite file storage path
- -(NSURL *) storeURL {
- // Obtain the database path
- // NSString * docs = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- /// CoreData is built on SQLite. The database name must be the same as the Xcdatamodel file.
- // NSURL * storeUrl = [NSURL fileURLWithPath: [docs stringByAppendingPathComponent: @ "CoreData. sqlite"];
-
- NSArray * export netdir = NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES );
- NSString * docDir = [opencnetdir objectAtIndex: 0];
- NSString * path = [docDir stringByAppendingPathComponent: @ "CoreData. sqlite"];
- NSURL * storeURL = [NSURL fileURLWithPath: path];
- Return storeURL;
- }
-
-
- // Initialize the database used by Core Data
- -(NSManagedObjectModel *) managedObjectModel
- {
- If (managedObjectModel! = Nil ){
- Return managedObjectModel;
- }
- Return [NSManagedObjectModel mergedModelFromBundles: nil];
- }
-
- // Initialize the value assignment function of managedObjectModel
- -(NSPersistentStoreCoordinator *) persistentStoreCoordinator
- {
- If (persistentStoreCoordinator! = Nil ){
- Return persistentStoreCoordinator;
- }
-
- NSError * error = nil;
- PersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
- InitWithManagedObjectModel: self. managedObjectModel];
- If (! [PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType
- Configuration: nil
- URL: [self storeURL]
- Options: nil
- Error: & error]) {
- NSLog (@ "Error: % @, % @", error, [error userInfo]);
- [NSException raise: @ "open failed" format: @ "Reason: % @", [error localizedDescription];
- }
-
- Return persistentStoreCoordinator;
- }
-
- // The initialization value assignment function of managedObjectContext
- -(NSManagedObjectContext *) managedObjectContext
- {
- If (managedObjectContext! = Nil ){
- Return managedObjectContext;
- }
-
- NSPersistentStoreCoordinator * coordinator = self. persistentStoreCoordinator;
-
- If (coordinator! = Nil ){
- ManagedObjectContext = [[NSManagedObjectContext alloc] init];
- [ManagedObjectContext setPersistentStoreCoordinator: coordinator];
- }
-
- Return managedObjectContext;
- }
-
- // Save the MTLModel object to coredata
- -(BOOL) saveMTLModel :( MTLModel *) MtlModel
- Error :( NSError * _ autoreleasing *) error {
- // ----- Need Add Remove the Entity First START ---------
- NSManagedObject * exsitManagedObject = [self getManagedObject: mtlModel
- Error: error];
- If (exsitManagedObject! = Nil ){
- [Self. managedObjectContext deleteObject: exsitManagedObject];
- [Self. managedObjectContext save: error];
- };
- // ----- Need Add Remove the Entity First END -----------
-
- NSManagedObject * managedObject = [MTLManagedObjectAdapter
- ManagedObjectFromModel: mtlModel
- Insertingtransfercontext: self. managedObjectContext
- Error: error];
-
- If (managedObject = nil ){
- NSLog (@ "[NSManagedObject] Error: % @", * error );
- Return NO;
- }
-
- If (! [Self. managedObjectContext save: error]) {
- NSLog (@ "[self. managedObjectContext] Error: % @", * error );
- Return NO;
- };
- Return YES;
- };
-
- // Extract MTLModel from coredata
- -(MTLModel *) getMTLmodel :( MTLModel *) MtlModel
- Error :( NSError * _ autoreleasing *) error {
-
- NSManagedObject * managedObject = [self getManagedObject: mtlModel error: error];
- MTLModel * mrlMotel = [[MTLModel alloc] init];
-
- MrlMotel = [MTLManagedObjectAdapter modelOfClass: [mtlModel class]
- FromManagedObject: managedObject error: error];
-
- If (error ){
- NSLog (@ "[mrlMotel] Error: % @", * error );
- }
- Return mrlMotel;
- };
-
- // Obtain the existing ManagedObject from coredata
- -(NSManagedObject *) getManagedObject :( MTLModel *) MtlModel
- Error :( NSError * _ autoreleasing *) error {
- NSString * entityName = [[mtlModel class] managedObjectEntityName];
-
- // Obtain the number of objects in entity
- NSFetchRequest * requestCount = [NSFetchRequest fetchRequestWithEntityName: entityName];
- NSUInteger count = [self. managedObjectContext countForFetchRequest: requestCount
- Error: error];
- NSLog (@ "count result: % d", count );
- NSLog (@ "sortDescriptor result: % @", [[mtlModel class] sortDescriptor]);
-
- // Obtain the first object in entity. This object must exist and be unique.
- If (count = 1 ){
- NSFetchRequest * request = [[NSFetchRequest alloc] init];
- [Request setEntity: [NSEntityDescription entityForName: entityName
- InManagedObjectContext: self. managedObjectContext];
- NSSortDescriptor * sort = [[mtlModel class] sortDescriptor];
- NSArray * sortDes = [[NSArray alloc] initWithObjects: sort, nil];
- [Request setSortDescriptors: sortDes];
- NSArray * getObject = [self. managedObjectContext
- ExecuteFetchRequest: request
- Error: error];
-
- Return [getObject objectAtIndex: 0];
- }
- Return nil;
- }
-
- // Delete the sqlite file from the file system
- -(Bool) deleteAllEntities {
- Bool status = NO;
- NSError * error;
- @ Try {
- [[NSFileManager defaultManager] removeItemAtPath: [self storeURL]. path
- Error: & error];
- Status = YES;
- }
- @ Catch (NSException * exception ){
- Status = NO;
- }
- @ Finally {
- Return status;
- }
- }
-
- @ End
3. Background execution Program[Objc]View plaincopyprint?
- -(Void) loadBannerList :( void (^) (NSArray * bannerList, NSError * error) block {
-
- NSParameterAssert (block );
-
- [Self POST: @ "webresources/homePage"
- Parameters: nil
- ResultClass: BannerWrapper. class
- ResultKeyPath: nil
- Completion: ^ (AFHTTPRequestOperation * operation, id responseObject, NSError * error ){
-
- // ----------------------- Persistence DEMO ---------------------
- // If network error, get data from CoreData, else save data into CoreData
- If (! Error ){
- NSError * err;
- Persistence * persistence = [[Persistence alloc] init];
- BOOL save = [persistence saveMTLModel: responseObject error: & err];
- If (save = NO ){
- NSLog (@ "Save ERROR! ");
- }
- } Else {
- NSError * err;
- Persistence * persistence = [[Persistence alloc] init];
- BannerWrapper * resObject = [[BannerWrapper alloc] init];
- BannerWrapper * object = [[BannerWrapper alloc] init];
- Object = [persistence getMTLmodel: resObject error: & err];
-
- ResponseObject = object;
-
- // This exception is strange. The Array type returned from coredata is changed to the set type, so a conversion is made temporarily.
- If ([object. bannerList isKindOfClass: [NSSet class]) {
- NSArray * objectArray = [(NSSet *) object. bannerList allObjects];
- (BannerWrapper *) responseObject). bannerList = objectArray;
- }
- }
- //-----------------------------------------------------------
-
- BannerWrapper * wrapper = responseObject;
- Block (wrapper. bannerList, error );
-
- }];
- }