Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary and Core Data

Please I am trying to gain some knowledge in core data. I have so far gotten the hang of creating entities and adding, retrieving and deleting values from this entity.

My question is the following. What are the possible ways of storing NSDictionary properties in an entity when using core data?

like image 288
user1889672 Avatar asked May 16 '13 17:05

user1889672


2 Answers

you should use "Transformable Attributes":

  1. open *.xcdatamodeld file
  2. select entity
  3. add attribute (name it for example "info") and set the type as "Transformable"
  4. generate appropriate NSManagedObject subclass files (File->New->File ... NSManagedObject subclass)
  5. open *.h file and change type for property "info" from id to NSMutableDictionary*

everything else works automatically

for more information see: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdNSAttributes.html

like image 197
funberry Avatar answered Sep 24 '22 03:09

funberry


There are several ways to approach this:

a. Create an entity that is representative of the NSDictionary, so that each dictionary key is represented by an entity attribute.

b. If you don't like the above approach where you create a separate entity, you can still store the NSDictionary into a single Core Data field of type NSData, provided that you serialize the NSDictionary to NSData first.

//NSDictionary to NSData
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:dictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
//  data is now ready to use

You'd also then need to convert the NSData back to NSDictionary when you read it from Core Data.

// NSData to NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *dictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
//  dictionary is now ready to use

c. Finally, you can use a persistance framework such as Sensible TableView, where all your data structures are automatically fetched, displayed, and saved. Saves me a ton of code myself.

like image 40
Matt Avatar answered Sep 24 '22 03:09

Matt