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?
you should use "Transformable Attributes":
*.xcdatamodeld
fileNSManagedObject
subclass files (File->New->File ... NSManagedObject
subclass)*.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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With