NSCoding of NSMutableDictionaries containing custom objects - ios

I was trying to serialize a SearchEntity object(custom object) containing an NSMutableDictionary containing a set of type CategoryEntity(custom object).
1 SearchEntity<NSCoding> containing:
1 NSMutableDictionary (parameters)
parameters containing
X CategoryEntities<NSCoding> containing just strings and numbers.
At this line [encoder encodeObject:parameters forKey:kPreviousSearchEntityKey]; in the SearchEntity encodeWithCoder" I get GDB:Interrupted every time, no error message, exception etc. just GDB:Interrupted.
This is the implementation in SearchEntity and parameters is the NSMutableDictionary
#pragma mark -
#pragma mark NSCoding delegate methods
- (void) encodeWithCoder:(NSCoder*)encoder
{
//encode all the values so they can be persisted in NSUserdefaults
if (parameters)
[encoder encodeObject:parameters forKey:kPreviousSearchEntityKey]; //GDB:Interrupted!
}
- (id) initWithCoder:(NSCoder*)decoder
{
if (self = [super init])
{
//decode all values to return an object from NSUserdefaults in the same state as when saved
[self setParameters:[decoder decodeObjectForKey:kPreviousSearchEntityKey]];
}
return self;
}
The CategoryEntity also implements the NSCoding protocol and looks like this:
- (void) encodeWithCoder:(NSCoder*)encoder
{
//encode all the values so they can be persisted in NSUserdefaults
[encoder encodeObject:ID forKey:kIDKey];
[encoder encodeObject:text forKey:kTextKey];
[encoder encodeObject:category forKey:kCategoryKey];
[encoder encodeObject:categoryIdentifierKey forKey:kCategoryIdentifierKey];
}
- (id) initWithCoder:(NSCoder*)decoder
{
if (self = [super init]) {
//decode all values to return an object from NSUserdefaults in the same state as when saved
[self setID:[decoder decodeObjectForKey:kIDKey]];
[self setText:[decoder decodeObjectForKey:kTextKey]];
[self setCategory:[decoder decodeObjectForKey:kCategoryKey]];
[self setCategoryIdentifierKey:[decoder decodeObjectForKey:kCategoryIdentifierKey]];
}
return self;
}
I try to encode it from a wrapper for NSUserDefaults, like this:
+ (void) setPreviousSearchParameters:(SearchParameterEntity*) entity
{
if (entity)
{
//first encode the entity (implements the NSCoding protocol) then save it
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:entity];
[[self defaults] setObject:encodedObject forKey:kPreviousSearchKey];
[[self defaults] synchronize];
}
}
+ (SearchParameterEntity*) getPreviousSearchParameters
{
//retrieve the encoded NSData object that was saved, decode and return it
SearchParameterEntity *entity = nil;
NSData *encodedObject = [[self defaults] objectForKey:kPreviousSearchKey];
if (encodedObject)
entity = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return entity;
}
I was thinking that when I ask to Serialize the SearchEntity, it would start to serialize the 'parameters' mutableDictionary object, NSCoder will call "encode" on the CategoryEntities contained in the dictionary and they will all respond with their correct encoded objects.
However I just get GDB:Interrupted in the bottom of the console.
How can I debug this?
And is my approach wrong, should I wrap all levels of encoding in NSData?
Ps. I do the exact same thing with a ResultEntity containing NSArrays of CategoryEntities, it encodes with no problems, so I guess the NSMutableDictionary is the only thing sticking out.

The code you have posted does not appear to be incorrect. I've made a best guess at some details you've left out and I get a successful result from a test program containing your code with enough boilerplate to show that it encodes/decodes correctly.
(You can compile it from the command line using: gcc -framework foundation test.m -o test and run with: ./test.)
With regard to your question, how can I debug this, I would suggest an approach as follows:
(Temporarily) modify your code to be as simple as possible. For example, you could change the parameters property to a plain NSString and verify that works correctly first.
Slowly add in complexity, introducing one new property at a time, until the error starts occurring again. Eventually you will narrow down where the troublesome data is coming from.
Alas, if this is occurring due to some mis-managed memory elsewhere in your app, debugging this code itself may not get you anywhere. Try (manually) verifying that memory is managed correctly for each piece of data you are receiving for encoding.
If you are already using Core Data you could consider persisting just the object ID in the user defaults and restore your object graph based on that. (See: Archiving NSManagedObject with NSCoding).

I suggest you to bypass the NSMutableArray first. Let SearchEntity contains only one CategoryEntity and see if it works.
The code you posted looks good, you may want to give us more detailed context.
For object encoding, this file may help: DateDetailEntry

The problem with archiving objects with NSKeyedArchiver is that you cannot encode mutable objects. Only instances of NSArray, NSDictionary, NSString, NSDate, NSNumber, and NSData (and some of their subclasses) can be serialized
So, in your SearchEntity method encodeWithCoder: you should try creating NSDictionary from NSMutableDictionary and then encoding the immutable one:
if (parameters) {
NSDictionary *dict = [NSDictionary dictionaryWithDictionary:parameters];
[encoder encodeObject:dict forKey:kPreviousSearchEntityKey];
}
Also in the initWithCoder: method try creating NSMutableDictionary from the encoded immutable one:
NSDictionary *dict = [decoder decodeObjectForKey:kPreviousSearchEntityKey];
[self setParameters:[NSMutableDictionary dictionaryWithDictionary:dict]];
Also check for all obejct within parameters dictionary to conform to NSCoding protocol and ensure that all of them encode only immutable objects in their encodeWithCoder: methods.
Hope it solves the problem.

Related

Save NSMutableArray in iOS

I need to save many NSMutableArray with my custom objects and I want to know what is the best way to do this.
Maybe NSUserDefaults is not the best way to do it.
What should I use?
If your array contains non-plist objects, then you cannot use NSUserDefaults without first encoding the array.
The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects.
You'll want to encode it using NSKeyedArchiver. This will give you an NSData object that you can then store in NSUserDefaults, or write it to file through NSKeyedArchiver itself.
All you have to do is conform to NSCoding in your custom object, and override initWithCoder: to initialise your object when it's loaded and encodeWithCoder: to encode your variables when it gets encoded. For example, your custom object will look something like this:
#interface customArrayObject : NSObject <NSCoding>
#property (nonatomic) NSString* foo;
#property (nonatomic) NSInteger bar;
#end
#implementation customArrayObject
-(instancetype) initWithCoder:(NSCoder *)aDecoder { // decode variables
if (self = [super init]) {
_foo = [aDecoder decodeObjectForKey:#"foo"];
_bar = [aDecoder decodeIntegerForKey:#"bar"];
}
return self;
}
-(void) encodeWithCoder:(NSCoder *)aCoder { // encode variables
[aCoder encodeObject:_foo forKey:#"foo"];
[aCoder encodeInteger:_bar forKey:#"bar"];
}
#end
It's also worth noting that NSUserDefaults is used to store user preferences, and therefore if your array contains data that isn't in any way to do with a user preference, you shouldn't be using NSUserDefaults - you should be writing it to disk yourself.
Writing your array to disk is actually a lot more trivial than it sounds, you can use the archiveRootObject:toFile: method on NSKeyedArchiver. For example, this will write your custom array to the documents directory:
// Gets the documents directory path
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES)[0];
// Archive and save the file to foo.dat in the documents directory. Returns whether the operation was successful.
BOOL success = [NSKeyedArchiver archiveRootObject:customArray toFile:[NSString stringWithFormat:#"%#/%#", documentsPath, #"foo.dat"]]
However, it is also worth noting that this flat (yes/no) as to whether the operation was successful isn't that great when it comes to error handling. If you want to implement custom error handling, then you'll want to first encode the object using NSKeyedArchiver's archivedDataWithRootObject: method, and then NSData's writeToFile:options:error: method.

Issue with initWithCoder: and NSKeyedUnarchiver

I'm currently attempting to add a game-saving feature to my app. The end goal is to get ~300 custom objects saved to a .plist file and extract them again later. I've made some headway, but I'm having some issues with initWithCoder: and I'm also unsure about my technique.
The following code is being used by a UIViewController to save the objects (I only added 2 objects to the dictionary as an example):
//Saves the contents to a file using an NSMutableDictionary
-(IBAction)saveContents {
//Create the dictionary
NSMutableDictionary *dataToSave = [NSMutableDictionary new];
//Add objects to the dictionary
[dataToSave setObject:label.text forKey:#"label.text"];
[dataToSave setObject:territory forKey:#"territory"];
[dataToSave setObject:territory2 forKey:#"territory2"];
//Archive the dictionary and its contents and set a BOOL to indicate if it succeeds
BOOL success = [NSKeyedArchiver archiveRootObject:dataToSave toFile:[self gameSaveFilePath]];
//Handle success/failure here...
//Remove and free the dictionary
[dataToSave removeAllObjects]; dataToSave = nil;
}
This successfully calls the encodeWithCoder: function in the Territory class twice:
-(void)encodeWithCoder:(NSCoder *)aCoder {
NSLog(#"ENCODING");
[aCoder encodeObject:self.data forKey:#"data"];
[aCoder encodeInt:self.MMHValue forKey:#"MMHValue"];
[aCoder encodeObject:self.territoryName forKey:#"territoryName"];
//Continue with other objects
}
When I look in the directory, sure enough, the file exists. Now, here's the issue I'm having: When the following function is run, the initWithCoder: function is successfully called twice as it should be. The logs inside the initWithCoder: function output what they should, but the logs in the UIViewController's loadContents function return 0, null, etc. However, the label's text is set correctly.
//Loads the contents from a file using an NSDictionary
-(IBAction)loadContents {
//Create a dictionary to load saved data into then load the saved data into the dictionary
NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithFile:[self gameSaveFilePath]];
//Load objects using the dictionary's data
label.text = [savedData objectForKey:#"label.text"];
NSLog(#"%i, %i", [territory intAtKey:#"Key4"], [territory2 intAtKey:#"Key4"]);
NSLog(#"MMH: %i, %i", territory.MMHValue, territory2.MMHValue);
NSLog(#"NAME: %#, %#", territory.territoryName, territory2.territoryName);
//Free the dictionary
savedData = nil;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
NSLog(#"DECODING TERRITORY");
self.data = [aDecoder decodeObjectForKey:#"data"];
self.MMHValue = [aDecoder decodeIntForKey:#"MMHValue"];
self.territoryName = [[aDecoder decodeObjectForKey:#"territoryName"] copy];
//Continue with other objects
}
NSLog(#"DECODED INT: %i", self.MMHValue);
NSLog(#"DECODED NAME: %#", self.territoryName);
return self;
}
I've been trying to get this to work for hours, but to no avail. If anyone has any insights to this, please help me out. Also, I'm not entirely sure if my technique for saving is good or not (using an NSMutableDictionary to store references to the objects so it can output to one file)? Thanks!
I read through Apple's documentation on NSKeyedArchiver and NSKeyedUnarchiver, along with a bunch of blog posts on the subject, and I realized what I was doing wrong. After encoding the objects to a file (by adding them to a dictionary using keys and then saving them to a .plist), when I tried decoding them, I never actually extracted the values from the new dictionary (the dictionary holding the contents of the file that was just decoded). This also explains why the label's text was loaded, but territory and territory2 weren't. I changed my loadContents function to the following, and now the code works:
-(IBAction)loadContents {
//Create a dictionary to load saved data into then load the saved data into the dictionary
NSLog(#"***** STARTING DECODE *****");
NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithFile:[self gameSaveFilePath]];
NSLog(#"***** CALLING initWithCoder: ON OBJECTS *****");
NSLog(#"***** FINISHED DECODE *****");
//Load objects using the dictionary's data
label.text = [savedData objectForKey:#"label.text"];
territory = [savedData objectForKey:#"territory"];
territory2 = [savedData objectForKey:#"territory2"];
//Free the dictionary
savedData = nil;
}

"Attempt to set a non-property list object...." NSMutableDictionary with custom class [duplicate]

This question already has answers here:
Write custom object to .plist in Cocoa
(3 answers)
Closed 9 years ago.
I have a custom class called ServerModule which is a subclass of NSObject. I'm basically storing all of these ServerModules with a key-value pair in an NSMutableDictionary. The dictionary is then stored in NSUserDefaults. I learned that NSUserDefaults only returns an immutable version of the object when it is accessed, so I changed my dictionary initialization to this:
_AllModules = [[NSMutableDictionary alloc]initWithDictionary:[_editServerModules objectForKey:#"AllModules"]]; //initialize a copy of AllModules dictionary
Now, I am simply trying to store a custom ServerModule object in this dictionary, and sync it. The following code attempts to do this:
//Create new ServerModule
ServerModule* newServer = [[ServerModule alloc]initWithUUID];
newServer.name = self.tf_name.text;
newServer.ip = self.tf_ip.text;
newServer.port = self.tf_port.text;
newServer.username = self.tf_user.text;
newServer.password = self.tf_pass.text;
//Add the ServerModule to AllModules dictionary with the key of its identifier
[_AllModules setObject:newServer forKey:newServer.identifier];
[self updateData];
[_editServerModules synchronize];
The identifier is a string which is set in the constructor of ServerModule. Here is the code for updateData.
[_editServerModules setObject:_AllModules forKey:#"AllModules"];
In case you are wondering, the object at #"AllModules" is initialized in the AppDelegate as follows:
NSMutableDictionary* AllModules = [[NSMutableDictionary alloc]init];
Once again, here is the error I am getting when I try to save something:
Attempt to set a non-property-list object {
"42E9EEA0-9051-4E2A-81EA-DC8FC5639C26" = "<ServerModule: 0x8ac4e50>";
} as an NSUserDefaults value for key AllModules
Thanks for any help!
~Carpetfizz
You can only store property list types (array, data, string, number, date, dictionary) or urls in NSUserDefaults. This means that everything, including any nested dictionary values, must be property list types. You'll want to implement the NSCoding protocol on your ServerModule object and then use NSKeyedArchiver to serialize your data before storing it and and NSKeyedUnarchiver to deflate your data after reading it back out of NSUserDefaults.
For example, given the properties you've shown exist on ServerModule objects, I'd add the following NSCoding protocol methods to your ServerModule implementation:
#pragma mark - NSCoding support
-(void)encodeWithCoder:(NSCoder*)encoder {
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.ip forKey:#"ip"];
[encoder encodeObject:self.port forKey:#"port"];
[encoder encodeObject:self.username forKey:#"username"];
[encoder encodeObject:self.password forKey:#"password"];
}
-(id)initWithCoder:(NSCoder*)decoder {
self.name = [decoder decodeObjectForKey:#"name"];
self.ip = [decoder decodeObjectForKey:#"ip"];
self.port = [decoder decodeObjectForKey:#"port"];
self.username = [decoder decodeObjectForKey:#"username"];
self.password = [decoder decodeObjectForKey:#"password"];
return self;
}
And then of course you'll need to serialize:
NSData* archivedServerModules = [NSKeyedArchiver archivedDataWithRootObject:_AllModules];
[_editServerModules setObject:archivedServerModules forKey:#"AllModules"];
and deflate appropriately:
NSData* archivedServerModules = [_editServerModules objectForKey:#"AllModules"];
NSDictionary* serverModules = [NSKeyedUnarchiver unarchiveObjectWithData:archivedServerModules];
Hopefully that gives you an idea of what I'm talking about.

How to use NSUserDefaults to store a container class

I'm trying to store a set of values under an NSUserDefaults key. I use a custom class to access an RSS feed and set the class's variables to match the info found in the feed. I then use another class to set the values under a NSUserDefaults key:
[infoStorageClass dataIsNew:self];
[infoStorageClass storeData:self];
The problem is that whenever I store my class I get this warning:
[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
"TARSSInfo: 0x80eb6a0"
)' of class '__NSArrayM'. Note that dictionaries and arrays in property lists must also contain only property values.
What's going on here? Thanks in advance for you help.
From documentation:
A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
In order to store an object of another type you first need to implement NSCoding protocol in the class of the object you want to store. Which means implement these methods and do decoding and encoding like this(a snippet of my own code of custom class BMDifficultyLevel):
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
_difficultyLevel = [decoder decodeObjectForKey:#"difficulty"];
_difficultyLevelType = [decoder decodeIntegerForKey:#"type"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:_difficultyLevel forKey:#"difficulty"];
[encoder encodeInteger:_difficultyLevelType forKey:#"type"];
}
then before storing your object you need to archive and then store like this:
NSUserDefaults *defaults = [[NSUserDefaults alloc] init];
_defaultsDataWithLevelObject = [NSKeyedArchiver archivedDataWithRootObject:_difficultyLevel];
[defaults setObject:_defaultsDataWithLevelObject forKey:BMDifficultyLevelDefaultsKey];
where _defaultsDataWithLevelObject is an object of type NSData, which means eventually you store NSData object.
To retrieve your defaults you'll need to unarchive the object something like this:
_defaultsDataWithLevelObject = [[NSUserDefaults standardUserDefaults] objectForKey:BMDifficultyLevelDefaultsKey];
_difficultyLevel = [NSKeyedUnarchiver unarchiveObjectWithData:_defaultsDataWithLevelObject];
You should make your custom class implement the NSCoding protocol and then archive your array of instances. This will give you an NSData instance that you can store into user defaults.

Why NSUserDefaults failed to save NSMutableDictionary in iOS?

I'd like to save an NSMutableDictionary object in NSUserDefaults. The key type in NSMutableDictionary is NSString, the value type is NSArray, which contains a list of object which implements NSCoding. Per document, NSString and NSArray both are conform to NSCoding.
I am getting this error:
[NSUserDefaults setObject: forKey:]: Attempt to insert non-property value.... of class NSCFDictionary.
I found out one alternative, before save, I encode the root object (NSArray object) using NSKeyedArchiver, which ends with NSData. Then use UserDefaults save the NSData.
When I need the data, I read out the NSData, and use NSKeyedUnarchiver to convert NSData back to the object.
It is a little cumbersome, because i need to convert to/from NSData everytime, but it just works.
Here is one example per request:
Save:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arr = ... ; // set value
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
[defaults setObject:data forKey:#"theKey"];
[defaults synchronize];
Load:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:#"theKey"];
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
The element in the array implements
#interface CommentItem : NSObject<NSCoding> {
NSString *value;
}
Then in the implementation of CommentItem, provides two methods:
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:value forKey:#"Value"];
}
-(id)initWithCoder:(NSCoder *)decoder
{
self.value = [decoder decodeObjectForKey:#"Value"];
return self;
}
Anyone has better solution?
Thanks everyone.
If you're saving an object in user defaults, all objects, recursively, all the way down, must be property list objects. Conforming to NSCoding doesn't mean anything here-- NSUserDefaults won't automatically encode them into NSData, you have to do that yourself. If your "list of object which implements NSCoding" means objects that are not property list objects, then you'll have to do something with them before saving to user defaults.
FYI the property list classes are NSDictionary, NSArray, NSString, NSDate, NSData, and NSNumber. You can write mutable subclasses (like NSMutableDictionary) to user preferences but the objects you read out will always be immutable.
Are all of your keys in the dictionary NSStrings? I think they have to be in order to save the dictionary to a property list.
Simplest Answer :
NSDictionary is only a plist object , if the keys are NSStrings.
So, Store the "Key" as NSString with stringWithFormat.
Solution :
NSString *key = [NSString stringWithFormat:#"%#",[dictionary valueForKey:#"Key"]];
Benefits :
It will add String-Value.
It will add Empty-Value when your Value of Variable is NULL.
Have you considered looking at implementing the NSCoding Protocol? This will allow you encode and decode on the iPhone with two simple methods that are implemented with the NSCoding. First you would need to adding the NSCoding to your Class.
Here is an example:
This is in the .h file
#interface GameContent : NSObject <NSCoding>
Then you will need to implement two methods of the NSCoding Protocol.
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
[self setFoundHotSpots:[coder decodeObjectForKey:#"foundHotSpots"]];
}
return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:foundHotSpots forKey:#"foundHotSpots"];
}
Check out the documentation on NSCoder for more information. That has come in really handy for my projects where I need to save the state of the application on the iPhone if the application is closed and restore it back to it's state when its back on.
The key is to add the protocol to the interface and then implement the two methods that are part of NSCoding.
I hope this helps!
There is no better solution. Another option would be to just save the coded object to disk - but that is doing the same thing. They both end up with NSData that gets decoded when you want it back.

Resources