insert NSDictionary into CoreData

23,729

Solution 1

You would need to serialize your NSDictionary to an NSData, CoreData can hold to NSData.
But you won't be able to search (predicate) element of your NSDictionary.

And if we think about this, NSDictionary is a collection of data.
A Table in a database is kind of a collection of data.
In CoreData the closest thing you got to a collection of data is NSManagedObject.

So my advice would be to make a NSManagedObject subclass that would hold the information you have in your NSDictionary. The key would be the attribute and the value would be the value of that attribute. And you would be able to search based on the attribute of that NSManagedObject subclass.

Solution 2

I found another way to add Dictionary into Coredata by creating an attribute with data type 'Transformable'.

For example create an entity in your project & attribute with data type Transformable. Generate subclass for NSManagedObject. Attribute will be available with data type 'id', change into NSDictionary.

Below is what I did (My NSManagedObject sub class name is 'DictTest')

-(void)InsertIntoDataBase
{
    DictTest *entityDict=(DictTest*)[NSEntityDescription insertNewObjectForEntityForName:@"DictTest" inManagedObjectContext:self.managedObjectContext];
    NSMutableDictionary *mutDict=[NSMutableDictionary dictionary];
    [mutDict setValue:@"1" forKey:@"1"];
    [mutDict setValue:@"2" forKey:@"2"];
    [mutDict setValue:@"3" forKey:@"3"];
    [mutDict setValue:@"4" forKey:@"4"];
    [mutDict setValue:@"5" forKey:@"5"];
    [mutDict setValue:@"6" forKey:@"6"];
    [mutDict setValue:@"7" forKey:@"7"];
    [mutDict setValue:@"8" forKey:@"8"];
    [mutDict setValue:@"9" forKey:@"9"];
    [mutDict setValue:@"10" forKey:@"10"];
    [entityDict setInfoDict:mutDict];
    NSError *error;
    if(![self.managedObjectContext save:&error])
    {
        NSLog(@"error description is : %@",error.localizedDescription);
    }
    else{
        NSLog(@"Saved");

    }
}

for Fetching records

-(void)FetchRecord
{
    NSFetchRequest *request=[[NSFetchRequest alloc]init];
    NSEntityDescription *entity=[NSEntityDescription entityForName:@"DictTest" inManagedObjectContext:self.managedObjectContext];
    [request setEntity:entity];
     NSArray *fetchArray=  [self.managedObjectContext executeFetchRequest:request error:nil];
    for (DictTest *obj in fetchArray) {
        NSLog(@"Dict is : %@",obj.infoDict);
    }
}

Solution 3

Set up your entity description, insert a new object, then use:

[managedObject setValuesForKeysWithDictionary:dict];

Solution 4

Why don't you just create an entity with all the data from your NSDictionary and then just parse through it.

Check this out for some CoreData code snippets. You can simply create a few entities to store the info of your dictionaries. You can then parse through your dictionary and save the proper attributes:

 NSManagedObject *photoObject = [NSEntityDescription insertNewObjectForEntityForName:@"Photo"
                                                              inManagedObjectContext:context];    
 [photoObject setPhotographer:[myDictionary objectForKey:@"photographer"]];
 and so on...

No matter how complex you XML data structure, if you can set up a nice entity structure, it is fairly easy to simply dumb it all in CoreData. You'll also have a much easier time with queries if you take the time to create entities instead of just dumping the whole dictionary in a single field.

Share:
23,729
OXXY
Author by

OXXY

I'm beginner in iOS development. i've started developing since June 2011. i am interested in developing for iPad

Updated on May 01, 2020

Comments

  • OXXY
    OXXY about 4 years

    I have an NSDictionary and a CoreData Database. I want to insert the NSDictionary into the database.

    1. How can I do this (code snippets if possible)?

    2. What is the suitable type for the attribute of the dictionary ?

  • OXXY
    OXXY over 12 years
    VinceBurn first i wanna thank you for the answer and second i wanna tell you that i escape from your solution to the NSDictionary because i received the data from a huge XML file so i want use a dynamic way to fill the data
  • Vincent Bernier
    Vincent Bernier over 12 years
    @OXXY - You're welcome. I'm not sure I'm following you, if your XML file is huge you can parse it to one or 2 or 3 different NSManagedObject subclass. Depending on the content of your XML you can modify your action. And that way you would be able to query it. If you don't need to query it you can save that file directly to disk, and store the URL in a core data object, that would almost be the same as storing it as a NSData. And if there is only one of those at a time don't use core data for persistence. I'm not sure what your architecture is so I may be out of line.
  • OXXY
    OXXY over 12 years
    I've put a question about parsing the XML and store it in the database maybe it will help you to follow me stackoverflow.com/questions/8518884/…
  • OXXY
    OXXY over 12 years
    dear Mattieu the answer for your why is on this question by me stackoverflow.com/questions/8518884/…
  • Vivek Gani
    Vivek Gani almost 10 years
    Note that this requires that the entity description have no missing pieces when using this method - see cimgf.com/2011/06/02/saving-json-to-core-data - "In this method, the keys contained in the dictionary determine what keys are used on the managed object. But what if the dictionary contains a key that’s not part of the entity description? Then your app crashes with an error about how the object is not key-value coding compliant for the key. Using this method here puts your app’s stability at the mercy of the web service you’re using."