程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Core Data with Mantle

Core Data with Mantle

編輯:C++入門知識

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.

本文使用mantle作data model,並使用其對coredata的interface創建數據持久化的過程。

操作過程很簡單,就是數據的轉換:

\

1.Manle data model

Mantle中用於持久化的方法:

// A MTLModel object that supports being serialized to and from Core Data as an

// NSManagedObject.

  • @protocol MTLManagedObjectSerializing
  • @required

    // The name of the Core Data entity that the receiver serializes to and

    // deserializes from.

    • + (NSString *)managedObjectEntityName;

      // Specifies how to map property keys to different keys on the receiver's

      // +managedObjectEntity.

      • + (NSDictionary *)managedObjectKeysByPropertyKey;

        .h 文件

        [objc] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
        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文件

          [objc] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
          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. //在從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 持久化類

            Coredata主要元素簡要介紹

            網上有很多圖,但,還是覺得一本書上的這個圖最好:

            \

            • 1, Managed Object Model
              Managed Object Model 是描述應用程序的數據模型,這個模型包含實體(Entity),特性(Property),讀取請求(Fetch Request)等。(下文都使用英文術語。)

              2,Managed Object Context
              Managed Object Context 參與對數據對象進行各種操作的全過程,並監測數據對象的變化,以提供對 undo/redo 的支持及更新綁定到數據的 UI。

              3,Persistent Store Coordinator
              Persistent Store Coordinator 相當於數據文件管理器,處理底層的對數據文件的讀取與寫入。一般我們無需與它打交道。

              4,Managed Object
              Managed Object 數據對象,與 Managed Object Context 相關聯。

            • 5,Controller
              圖中綠色的 Array Controller, Object Controller, Tree Controller 這些控制器,一般都是通過 control+drag 將 Managed Object Context 綁定到它們,這樣我們就可以在 nib 中可視化地操作數據。

              .h文件

              [objc] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
              1. #import
              2. @interface Persistence : NSObject
              3. //數據模型對象
              4. @property(strong,nonatomic) NSManagedObjectModel *managedObjectModel;
              5. //上下文對象
              6. @property(strong,nonatomic) NSManagedObjectContext *managedObjectContext;
              7. //持久性存儲區
              8. @property(strong,nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
              9. //確定sqlite文件存儲路徑
              10. -(NSURL *)storeURL;
              11. //初始化Core Data使用的數據庫
              12. -(NSPersistentStoreCoordinator *)persistentStoreCoordinator;
              13. //managedObjectModel的初始化賦值函數
              14. -(NSManagedObjectModel *)managedObjectModel;
              15. //managedObjectContext的初始化賦值函數
              16. -(NSManagedObjectContext *)managedObjectContext;
              17. //保存MTLModel對象至coredata
              18. -(BOOL)saveMTLModel:(MTLModel *)mtlModel
              19. error:(NSError * __autoreleasing *)error;
              20. //從coredata中提取出MTLModel
              21. -(MTLModel *)getMTLmodel:(MTLModel *)mtlModel
              22. error:(NSError *__autoreleasing *)error;
              23. //+ (NSFetchRequest *)fetchRequest;
              24. @end



                .m文件

                [objc] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
                1. #import "Persistence.h"
                2. @implementation Persistence
                3. @synthesize managedObjectContext;
                4. @synthesize managedObjectModel;
                5. @synthesize persistentStoreCoordinator;
                6. //確定sqlite文件存儲路徑
                7. -(NSURL *)storeURL{
                8. //得到數據庫的路徑
                9. // NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                10. // //CoreData是建立在SQLite之上的,數據庫名稱需與Xcdatamodel文件同名
                11. // NSURL *storeUrl = [NSURL fileURLWithPath:[docs stringByAppendingPathComponent:@"CoreData.sqlite"]];
                12. NSArray *documnetDir=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
                13. NSString *docDir=[documnetDir objectAtIndex:0];
                14. NSString *path=[docDir stringByAppendingPathComponent:@"CoreData.sqlite"];
                15. NSURL *storeURL=[NSURL fileURLWithPath:path];
                16. return storeURL;
                17. }
                18. //初始化Core Data使用的數據庫
                19. -(NSManagedObjectModel *)managedObjectModel
                20. {
                21. if (managedObjectModel != nil) {
                22. return managedObjectModel;
                23. }
                24. return [NSManagedObjectModel mergedModelFromBundles:nil];
                25. }
                26. //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. //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. //保存MTLModel對象至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. insertingIntoContext: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. //從coredata中提取出MTLModel
                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. //從coredata中獲取已存的ManagedObject
                96. -(NSManagedObject *)getManagedObject:(MTLModel *)mtlModel
                97. error:(NSError *__autoreleasing *)error{
                98. NSString *entityName=[[mtlModel class] managedObjectEntityName];
                99. //獲取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. //獲取entity中第一個對象.這個對象必須存在且唯一。
                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 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. //從文件系統中刪除sqlite文件
                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.後台執行程序

                  [objc] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片
                  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. //這個地方異常的奇怪,從coredata中應該返回打Array類型變成了set類型,所以這裡暫時作了一個轉換。
                  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. }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved