我得到JSON的响应存储在一个数组中,我想存储这些值
核心数据中的{albumId albumName coverPhotoURL createdDate}
请帮助我。
(
{
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;
}
)
答案 0 :(得分:0)
您需要创建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]);
}
}
答案 1 :(得分:0)
然后创建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);
}
答案 2 :(得分:0)
我想建议importing data using MagicalRecord是CoreData的优秀包装器。它提供了数据导入配置方法的约定。
导入功能能够映射数据,即使json模型中的属性与实体相比不同,或者您希望将字符串中表示的日期转换为NSDate
为避免重复输入,MagicalRecord将其作为使用uniqueID的约定。它期望实体Album的uniqueID属性,如albumID,Employee - employeeID等。因此需要按照惯例对其进行建模。根据你的情况,模型就是这样的。
您可以注意到,在albumID
的用户信息中,该属性已映射到albumId。同样地,createdDate
不是字符串值,而是NSDate
。
dateFormat
设置为createdDate
现在配置部分已完成。您可以将日期导入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);