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.
Related
This question already has answers here:
Convert any Data Type into NSData and back again
(1 answer)
NSData on custom class?
(1 answer)
Closed 6 years ago.
I'm trying to transfer data between 2 devices using bluetooth. I want to convert custom NSObject to NSData.
What is the best way to decode the received NSData into a custom NSObject ?
Thanks!
You have to use NSCoding. NSCoding is a simple protocol, with two methods: initWithCoder: and encodeWithCoder:. Classes that conform to NSCoding can be serialized and deserialized into data that can be either be archived to disk or distributed across a network.
NSCoding / NSKeyed​Archiver.
Here is tutorial of NSCoding.
Archiving
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:YourClass];
Unarchiving
YourClass *objYourClass = [NSKeyedUnarchiver unarchiveObjectWithData:data];
You can also refer my answer. First you have to create Bean Class and implement initWithCoder: and encodeWithCoder: after that you can Archive NSData from bean class object and Unarchive bean class object from NSData.
My very simple answer
First we have to implement the encodeWithCoder and initWithCoder in NSObject.m and before that I have 2 data(username and password) in NSObject Class.For example I set this.You can understand
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:#"Dev" forKey:#"username"];
[encoder encodeObject:#"Test#123" forKey:#"password"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
if((self = [super init]))
{
//decode properties, other class vars
userName = [decoder decodeObjectForKey:#"username"];
passWord = [decoder decodeObjectForKey:#"password"];
}
return self;
}
Then in ViewController.m
For Save
NSObjectClass *className = [[NSObjectClass alloc]init];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:className];
[currentDefaults setObject:data forKey:#"DATA"];
[currentDefaults synchronize];
For Retrieve
NSData *data = [currentDefaults objectForKey:#"DATA"];
className = [NSKeyedUnarchiver unarchiveObjectWithData:data];
For More Details Go through My ANSWER
I created a custom class to display in a TableView, I read a custom class object's array in TableView. Now, when I close the app I lose my date. I want to save that data permanently. But when I try to do so, I get the following error:
Attempt to set a non-property-list object as an NSUserDefaults
My code is:
#implementation CAChallangeListViewController
- (void)loadInitialData{
self.challangeItems = [[NSUserDefaults standardUserDefaults] objectForKey:#"challanges"];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[NSUserDefaults standardUserDefaults] setObject:self.challangeItems forKey:#"challanges"];
}
Here, the self. Challange items is a NSMutable array which contains objects of type CAChallange which is a custom class with following interface.
#interface CAChallange : NSObject
#property NSString *itemName;
#property BOOL *completed;
#property (readonly) NSDate *creationDate;
#end
You can easily accomplish what you are doing by converting your object into a standard dictionary (and back when you need to read it).
NSMutableArray *itemsToSave = [NSMutableArray array];
for (CAChallange *ch in myTableItems) {
[itemsToSave addObject:#{ #"itemName" : ch.itemName,
#"completed" : #(ch.completed),
#"creationDate" : ch.creationDate }];
}
You can use NSKeyedArchiver to create an NSData representation of your object. Your class will need to conform to the NSCoding protocol, which can be a bit tedious, but the AutoCoding category can do the work for you. After adding that to your project, you can easily serialize your objects like this:
id customObject = // Your object to persist
NSData *customObjectData = [NSKeyedArchiver archivedDataWithRootObject:customObject];
[[NSUserDefaults standardUserDefaults] setObject:customObjectData forKey:#"PersistenDataKey"];
And deserialize it like this:
NSData *customObjectData = [[NSUserDefaults standardUserDefaults] objectForKey:#"PersistenDataKey"];
id customObject = [NSKeyedUnarchiver unarchiveObjectWithData:customObjectData];
Your CAChallange object has a pointer to a BOOL which is not a suitable type for a plist:-
#property BOOL *completed
This is probably causing the error. You cannot store raw pointers in a plist.
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.
I try to save my object to NSUserDefaults. But when I call this method again it is not have any info about previous operation.
There is my method below:
- (void)addToCart {
if([[NSUserDefaults standardUserDefaults] objectForKey:kCart]) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *products = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:kCart]];
[products addObject:self.product];
[prefs setObject:products forKey:kCart];
[prefs synchronize];
[products release];
}
else {
//Saving...
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSArray arrayWithObjects:self.product, nil] forKey:kCart];
[prefs synchronize];
}
}
I need to save a collection with a products to NSUserDefault. I wrap my object to NSArray and save it but it doesn't work.
Everything put into NSUserDefaults must be a valid property list object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary). All collection elements must themselves also be property list objects.
In order to save non-PL objects into NSUserDefaults, you must first convert the object into a PL object. The most generic way to do this is by serializing it to NSData.
Serializing to NSData is handled with NSKeyedArchiver. See Storing NSColor in User Defaults for the canonical example of this. (That document is very old and still references NSArchiver which will work fine for this problem, but NSKeyedArchiver is now the preferred serializer.)
In order to archive using NSKeyedArchiver, your object must conform to NSCoding as noted by #harakiri.
You need to conform to the <NSCoding> protocol and implement -initWithCoder: and -encodeWithCoder: in your custom object.
See: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html
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.