Core Data with Mantle

Source: Internet
Author: User

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?
        1. # Import
        2. @ Interface BannerWrapper: MTLModel
        3. @ Property (nonatomic, readonly) bool result;
        4. @ Property (copy, nonatomic, readonly) NSNumber * resultId;
        5. @ Property (copy, nonatomic, readonly) NSString * resultMsg;
        6. @ Property (copy, nonatomic) NSArray * bannerList;
        7. + (NSSortDescriptor *) sortDescriptor;
        8. @ End
        9. @ Interface Banner: MTLModel
        10. @ Property (copy, nonatomic, readonly) NSNumber * bannerId;
        11. @ Property (copy, nonatomic, readonly) NSString * picUrl;
        12. @ Property (copy, nonatomic, readonly) NSString * toDetailUrl;
        13. @ Property (copy, nonatomic, readonly) NSNumber * width;
        14. @ Property (copy, nonatomic, readonly) NSNumber * height;
        15. @ End

          . M file

          [Objc]View plaincopyprint?
          1. # Import "Banner. h"
          2. @ Implementation BannerWrapper
          3. # Pragma mark-JSON serialization
          4. + (NSDictionary *) JSONKeyPathsByPropertyKey {
          5. Return @{
          6. @ "Result": @ "result ",
          7. @ "ResultId": @ "resultId ",
          8. @ "ResultMsg": @ "resultMSG ",
          9. @ "BannerList": @ "banner"
          10. };
          11. }
          12. + (NSValueTransformer *) bannerListJSONTransformer
          13. {
          14. Return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass: [Banner class];
          15. }
          16. # Pragma mark-Managed object serialization
          17. + (NSString *) managedObjectEntityName {
          18. Return @ "BannerWrapper ";
          19. }
          20. + (NSDictionary *) managedObjectKeysByPropertyKey {
          21. Return nil;
          22. }
          23. + (NSDictionary *) relationshipModelClassesByPropertyKey {
          24. Return @{
          25. @ "BannerList": [Banner class],
          26. };
          27. }
          28. // Data sorting method when retrieving data from coredata
          29. + (NSSortDescriptor *) sortDescriptor {
          30. Return [[NSSortDescriptor alloc] initWithKey: @ "resultId" ascending: YES];
          31. }
          32. @ End
          33. @ Implementation Banner
          34. # Pragma mark-JSON serialization
          35. + (NSDictionary *) JSONKeyPathsByPropertyKey {
          36. Return @{
          37. @ "BannerId": @ "id ",
          38. @ "PicUrl": @ "picUrl ",
          39. @ "ToDetailUrl": @ "toDetailUrl ",
          40. @ "Width": @ "width ",
          41. @ "Height": @ "height"
          42. };
          43. }
          44. # Pragma mark-Managed object serialization
          45. + (NSString *) managedObjectEntityName {
          46. Return @ "Banner ";
          47. }
          48. + (NSDictionary *) managedObjectKeysByPropertyKey {
          49. Return nil;
          50. }
          51. @ 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?
              1. # Import
              2. @ Interface Persistence: NSObject
              3. // Data model object
              4. @ Property (strong, nonatomic) NSManagedObjectModel * managedObjectModel;
              5. // Context object
              6. @ Property (strong, nonatomic) NSManagedObjectContext * managedObjectContext;
              7. // Persistent storage Zone
              8. @ Property (strong, nonatomic) NSPersistentStoreCoordinator * persistentStoreCoordinator;
              9. // Determine the sqlite file storage path
              10. -(NSURL *) storeURL;
              11. // Initialize the database used by Core Data
              12. -(NSPersistentStoreCoordinator *) persistentStoreCoordinator;
              13. // Initialize the value assignment function of managedObjectModel
              14. -(NSManagedObjectModel *) managedObjectModel;
              15. // The initialization value assignment function of managedObjectContext
              16. -(NSManagedObjectContext *) managedObjectContext;
              17. // Save the MTLModel object to coredata
              18. -(BOOL) saveMTLModel :( MTLModel *) MtlModel
              19. Error :( NSError * _ autoreleasing *) error;
              20. // Extract MTLModel from coredata
              21. -(MTLModel *) getMTLmodel :( MTLModel *) MtlModel
              22. Error :( NSError * _ autoreleasing *) error;
              23. // + (NSFetchRequest *) fetchRequest;
              24. @ End



                . M file

                [Objc]View plaincopyprint?
                1. # Import "Persistence. h"
                2. @ Implementation Persistence
                3. @ Synthesize managedObjectContext;
                4. @ Synthesize managedObjectModel;
                5. @ Synthesize persistentStoreCoordinator;
                6. // Determine the sqlite file storage path
                7. -(NSURL *) storeURL {
                8. // Obtain the database path
                9. // NSString * docs = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                10. /// CoreData is built on SQLite. The database name must be the same as the Xcdatamodel file.
                11. // NSURL * storeUrl = [NSURL fileURLWithPath: [docs stringByAppendingPathComponent: @ "CoreData. sqlite"];
                12. NSArray * export netdir = NSSearchPathForDirectoriesInDomains (NSDocumentationDirectory, NSUserDomainMask, YES );
                13. NSString * docDir = [opencnetdir objectAtIndex: 0];
                14. NSString * path = [docDir stringByAppendingPathComponent: @ "CoreData. sqlite"];
                15. NSURL * storeURL = [NSURL fileURLWithPath: path];
                16. Return storeURL;
                17. }
                18. // Initialize the database used by Core Data
                19. -(NSManagedObjectModel *) managedObjectModel
                20. {
                21. If (managedObjectModel! = Nil ){
                22. Return managedObjectModel;
                23. }
                24. Return [NSManagedObjectModel mergedModelFromBundles: nil];
                25. }
                26. // Initialize the value assignment function of managedObjectModel
                27. -(NSPersistentStoreCoordinator *) persistentStoreCoordinator
                28. {
                29. If (persistentStoreCoordinator! = Nil ){
                30. Return persistentStoreCoordinator;
                31. }
                32. NSError * error = nil;
                33. PersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
                34. InitWithManagedObjectModel: self. managedObjectModel];
                35. If (! [PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType
                36. Configuration: nil
                37. URL: [self storeURL]
                38. Options: nil
                39. Error: & error]) {
                40. NSLog (@ "Error: % @, % @", error, [error userInfo]);
                41. [NSException raise: @ "open failed" format: @ "Reason: % @", [error localizedDescription];
                42. }
                43. Return persistentStoreCoordinator;
                44. }
                45. // The initialization value assignment function of managedObjectContext
                46. -(NSManagedObjectContext *) managedObjectContext
                47. {
                48. If (managedObjectContext! = Nil ){
                49. Return managedObjectContext;
                50. }
                51. NSPersistentStoreCoordinator * coordinator = self. persistentStoreCoordinator;
                52. If (coordinator! = Nil ){
                53. ManagedObjectContext = [[NSManagedObjectContext alloc] init];
                54. [ManagedObjectContext setPersistentStoreCoordinator: coordinator];
                55. }
                56. Return managedObjectContext;
                57. }
                58. // Save the MTLModel object to coredata
                59. -(BOOL) saveMTLModel :( MTLModel *) MtlModel
                60. Error :( NSError * _ autoreleasing *) error {
                61. // ----- Need Add Remove the Entity First START ---------
                62. NSManagedObject * exsitManagedObject = [self getManagedObject: mtlModel
                63. Error: error];
                64. If (exsitManagedObject! = Nil ){
                65. [Self. managedObjectContext deleteObject: exsitManagedObject];
                66. [Self. managedObjectContext save: error];
                67. };
                68. // ----- Need Add Remove the Entity First END -----------
                69. NSManagedObject * managedObject = [MTLManagedObjectAdapter
                70. ManagedObjectFromModel: mtlModel
                71. Insertingtransfercontext: self. managedObjectContext
                72. Error: error];
                73. If (managedObject = nil ){
                74. NSLog (@ "[NSManagedObject] Error: % @", * error );
                75. Return NO;
                76. }
                77. If (! [Self. managedObjectContext save: error]) {
                78. NSLog (@ "[self. managedObjectContext] Error: % @", * error );
                79. Return NO;
                80. };
                81. Return YES;
                82. };
                83. // Extract MTLModel from coredata
                84. -(MTLModel *) getMTLmodel :( MTLModel *) MtlModel
                85. Error :( NSError * _ autoreleasing *) error {
                86. NSManagedObject * managedObject = [self getManagedObject: mtlModel error: error];
                87. MTLModel * mrlMotel = [[MTLModel alloc] init];
                88. MrlMotel = [MTLManagedObjectAdapter modelOfClass: [mtlModel class]
                89. FromManagedObject: managedObject error: error];
                90. If (error ){
                91. NSLog (@ "[mrlMotel] Error: % @", * error );
                92. }
                93. Return mrlMotel;
                94. };
                95. // Obtain the existing ManagedObject from coredata
                96. -(NSManagedObject *) getManagedObject :( MTLModel *) MtlModel
                97. Error :( NSError * _ autoreleasing *) error {
                98. NSString * entityName = [[mtlModel class] managedObjectEntityName];
                99. // Obtain the number of objects in entity
                100. NSFetchRequest * requestCount = [NSFetchRequest fetchRequestWithEntityName: entityName];
                101. NSUInteger count = [self. managedObjectContext countForFetchRequest: requestCount
                102. Error: error];
                103. NSLog (@ "count result: % d", count );
                104. NSLog (@ "sortDescriptor result: % @", [[mtlModel class] sortDescriptor]);
                105. // Obtain the first object in entity. This object must exist and be unique.
                106. If (count = 1 ){
                107. NSFetchRequest * request = [[NSFetchRequest alloc] init];
                108. [Request setEntity: [NSEntityDescription entityForName: entityName
                109. InManagedObjectContext: self. managedObjectContext];
                110. NSSortDescriptor * sort = [[mtlModel class] sortDescriptor];
                111. NSArray * sortDes = [[NSArray alloc] initWithObjects: sort, nil];
                112. [Request setSortDescriptors: sortDes];
                113. NSArray * getObject = [self. managedObjectContext
                114. ExecuteFetchRequest: request
                115. Error: error];
                116. Return [getObject objectAtIndex: 0];
                117. }
                118. Return nil;
                119. }
                120. // Delete the sqlite file from the file system
                121. -(Bool) deleteAllEntities {
                122. Bool status = NO;
                123. NSError * error;
                124. @ Try {
                125. [[NSFileManager defaultManager] removeItemAtPath: [self storeURL]. path
                126. Error: & error];
                127. Status = YES;
                128. }
                129. @ Catch (NSException * exception ){
                130. Status = NO;
                131. }
                132. @ Finally {
                133. Return status;
                134. }
                135. }
                136. @ End

                  3. Background execution Program

                  [Objc]View plaincopyprint?
                  1. -(Void) loadBannerList :( void (^) (NSArray * bannerList, NSError * error) block {
                  2. NSParameterAssert (block );
                  3. [Self POST: @ "webresources/homePage"
                  4. Parameters: nil
                  5. ResultClass: BannerWrapper. class
                  6. ResultKeyPath: nil
                  7. Completion: ^ (AFHTTPRequestOperation * operation, id responseObject, NSError * error ){
                  8. // ----------------------- Persistence DEMO ---------------------
                  9. // If network error, get data from CoreData, else save data into CoreData
                  10. If (! Error ){
                  11. NSError * err;
                  12. Persistence * persistence = [[Persistence alloc] init];
                  13. BOOL save = [persistence saveMTLModel: responseObject error: & err];
                  14. If (save = NO ){
                  15. NSLog (@ "Save ERROR! ");
                  16. }
                  17. } Else {
                  18. NSError * err;
                  19. Persistence * persistence = [[Persistence alloc] init];
                  20. BannerWrapper * resObject = [[BannerWrapper alloc] init];
                  21. BannerWrapper * object = [[BannerWrapper alloc] init];
                  22. Object = [persistence getMTLmodel: resObject error: & err];
                  23. ResponseObject = object;
                  24. // This exception is strange. The Array type returned from coredata is changed to the set type, so a conversion is made temporarily.
                  25. If ([object. bannerList isKindOfClass: [NSSet class]) {
                  26. NSArray * objectArray = [(NSSet *) object. bannerList allObjects];
                  27. (BannerWrapper *) responseObject). bannerList = objectArray;
                  28. }
                  29. }
                  30. //-----------------------------------------------------------
                  31. BannerWrapper * wrapper = responseObject;
                  32. Block (wrapper. bannerList, error );
                  33. }];
                  34. }

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.