【问题标题】:How to Store JSON Data in Core Data in iOS如何在 iOS 的 Core Data 中存储 JSON 数据
【发布时间】:2014-11-08 18:55:44
【问题描述】:

我从 JSON 获得的响应存储在一个数组中,我想存储这些值 {albumId albumName coverPhotoURL createdDate} 在 Core Data 中请帮助我。

    (
        {
        albumId = 1;
        albumName = UAE;
        coverPhotoURL = "http://1-dot-digiphoto-01.appspot.com/serve?blob-key=AMIfv95XeG-ii4aKZsUB5w-ClP0QUhJZa-o5BQRvdqArCCwg0Ueb13-wAfmyNHgaDdTaFS152_kXkJg5_9386zlfRCDc3fagW7Ekagdd6_VvJl6IscqNkyvVkXKYAqIRe-KqDMpjG-cW";
        createdDate = "10-Jun-2010 06:11 PM";
        description = "photos took in Dubai";
        lastViewedDate = "10-Jun-2010 06:11 PM";
        modifiedDate = "10-Jun-2010 06:11 PM";
        numberOfPhotos = 10;
       }
   )

【问题讨论】:

  • 您需要创建一个具有所需属性的实体,然后将此 JSON 映射到它。
  • 您可以尝试使用 MagicalRecord,它是 CoreData 的出色包装器。 cimgf.com/2012/05/29/importing-data-made-easy
  • @Chenna,如果你这样做了,有什么问题?

标签: ios core-data ios7


【解决方案1】:

您需要创建 NSManagedObject 的子类并定义所有需要的字段

@interface AlbumInfo : NSManagedObject

@property (nonatomic, retain) NSNumber * albumId;
@property (nonatomic, retain) NSString * albumName;
@property (nonatomic, retain) NSString * coverPhotoURL;
@property (nonatomic, retain) NSDate * createdDate;

@end

那么你需要调用这段代码

context = /* Get the NSManagedObject context */

AlbumInfo *item = [NSEntityDescription insertNewObjectForEntityForName:@"AlbumInfo" inManagedObjectContext:context];

item.albumId = @"some value from json";
/* ... so on ...*/

NSError *error = nil;
if (context != nil) {
    if ([managedObjectContext hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
} 

【讨论】:

    【解决方案2】:
    • 我假设您创建了一个适合您需要存储的数据的实体。
    • 然后创建NSEntityDescriptionNSManagedObject 以开始将您的对象加载到Core Data

      NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"ALbum" inManagedObjectContext:self.managedObjectContext];
      NSManagedObject *newAlbum = [[NSManagedObject alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
      
    • 那么你应该在托管对象中设置值

      [newPerson setValue:@"photos took in Dubai" forKey:@"description"];
      
      [newPerson setValue:@" UAE" forKey:@"albumName"];
      
    • 最后一步,您应该像这样保存这些更改

      NSError *error = nil;
      
      if (![newAlbum.managedObjectContext save:&error]) {
      
          NSLog(@"Unable to save managed object context.");
          NSLog(@"%@, %@", error, error.localizedDescription);
      }
      

    【讨论】:

    【解决方案3】:

    我想建议 importing data using MagicalRecord 一个优秀的 CoreData 包装器。它提供了数据导入配置方法的约定。

    导入功能能够映射数据,即使您的 json 模型中的属性与实体相比不同,或者您希望将字符串中表示的日期转换为 NSDate

    为避免重复条目,MagicalRecord 约定使用 uniqueID。即,它需要一个实体专辑的唯一ID 属性,如专辑ID、员工-员工ID 等。因此需要按照惯例对其进行建模。根据您的案例模型将是这样的。

    可以注意到albumID的User Info中,该属性映射到了albumId。同样,createdDate 不是字符串值,而是NSDate

    dateFormat 设置为 createdDate 的 UserInfo

    现在配置部分已经完成。您可以将日期导入 CoreData,如

    NSData *jsonData = //Data from web service;
    NSArray *albums = [NSJSONSerialization JSONObjectWithData:jsonData
                                                      options:0
                                                        error:nil];
    for (id obj in albums) {
        [Album MR_importFromObject:obj];
    }
    

    检查数据是否正确导入

    NSArray *savedAlbums = [Album MR_findAll];
    Album *album = [savedAlbums lastObject];
    NSLog(@"Created Date : %@",album.createdDate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-07
      • 2011-01-17
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 2014-10-14
      相关资源
      最近更新 更多