[英]How to Store JSON Data in Core Data in iOS
我正在从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;
}
)
您需要创建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]);
}
}
然后创建NSEntityDescription
和NSManagedObject
开始将您的对象加载到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); }
我想建议使用MagicalRecord导入数据,这是CoreData的出色包装。 它提供了有关数据导入配置方法的约定。
导入功能能够映射数据,即使您的json模型中的属性与实体相比有所不同,或者您想将字符串中表示的日期转换为NSDate
为了避免重复输入,MagicalRecord约定使用唯一ID。 即,它期望实体相册的唯一ID属性,例如AlbumID,Employee-employeeID等。因此,需要按照惯例对其进行建模。 根据您的案例模型将是这样。
您可以注意到,在albumID
的用户信息中,该属性已映射到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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.