如何使用魔法记录存储字典数组中的数据

时间:2016-06-08 07:40:02

标签: ios objective-c xcode

我正在尝试以数组字典的形式存储数据获取的API。我想将这些值存储在我的数据库中。 API响应存储在对象中。

[
  {
    "sort_priority": 1,
    "desc": "",
    "img_url": "",
    "id": 3,
    "name": "First Run"
  },
  {
    "sort_priority": 2,
    "desc": "",
    "img_url": "",
    "id": 4,
    "name": "Shorts"
  },
  {
    "sort_priority": 3,
    "desc": "",
    "img_url": "",
    "id": 1,
    "name": "Animation"
  },
  {
    "sort_priority": 4,
    "desc": "",
    "img_url": "",
    "id": 2,
    "name": "Documentary"
  }
]

我只想存储此列表中的名称和ID。

[Categories MR_importFromObject:responseObject];

Categories是一个实体,responseObject是从API返回的对象

2 个答案:

答案 0 :(得分:0)

for (int i=0; i<resultArr.count; i++)
    {
            NSError *error=nil;
            NSManagedObjectContext *context=[self managedObjectContext];
            NSManagedObject *newDevice=[NSEntityDescription insertNewObjectForEntityForName:@"myEntity" inManagedObjectContext:context];


            [newDevice setValue:[[resultArr objectAtIndex:i ]valueForKey:@"name"] forKey:@"name"] ;
            [newDevice setValue:[[resultArr objectAtIndex:i ]valueForKey:@"id"]  forKey:@"id"];


            [newDevice.managedObjectContext save:&error]) 


}

  //For fetchig/////////////////////

  NSError *error;
_dataEntity = [NSEntityDescription entityForName:@"myEntity" inManagedObjectContext:appDelegate.managedObjectContext];
NSFetchRequest * fr = [[NSFetchRequest alloc]init];
[fr setEntity:_dataEntity];
NSMutableArray *namesArr=[[NSMutableArray alloc]init];
NSMutableArray * result = [[appDelegate.managedObjectContext executeFetchRequest:fr error:&error] mutableCopy];
for (unsigned short int i=0;i<result.count;i++)
{
    NSMutableDictionary *coreDataDict=[[NSMutableDictionary alloc] init];
    NSManagedObject *fetchResult=[result  objectAtIndex:i];

    [coreDataDict setValue:[fetchResult valueForKey:@"name"] forKey:@"name"];


    [namesArr addObject:coreDataDict];

}

答案 1 :(得分:0)

感谢我的所有问题都解决了这个问题

NSArray *responseArray = (NSArray *)responseObject;
[Categories MR_importFromArray:responseArray];

我在array中有多个dictionary responseObject,并且只想存储每个dictionary的特定值。所以我上面提到它并且它在数据库中存储了正面。