Mutable Objects inside NSUserDefaults - ios

I created a simple database and put in NSUserDefaults. My database is NSMutableArray which has dictionaries and arrays inside in it. When I create NSMutableArray from NSUSerDefaults I can't add any objects to my mutable objects inside my NSMutableArray. Here is my code:
NSMutableArray *arrayOne = [NSMutableArray arrayWithContentsOfFile:[self createEditableCopyOfIfNeededWithFileName:#"Form.plist"]];
NSUserDefaults *ayarlar = [NSUserDefaults standardUserDefaults];
[ayarlar setObject:arrayOne forKey:#"form"];
NSMutableArray *arrayTwo = [NSMutableArray arrayWithArray:[[ayarlar objectForKey:#"form"] mutableCopy]];
[[[arrayTwo objectAtIndex:0] objectForKey:#"itemlar"] addObject:#"hop"];
And here is the error:
'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
How can I make this work? Thank you everyone.

NSUserDefaults is not the right place to store your data. First of all it should only be used for very small amounts of data, such as settings. And secondly it always returns immutable objects, even if you set mutable ones. Making a mutable copy of your first array doesn’t help because only the array will be mutable. Everything that is inside that array isn’t touched by the mutableCopy method and stay immutable.
You should use the NSPropertyListSerialization class to read and write your data from a file. On reading you can pass options controlling the mutability of the read objects. There you will want to pass NSPropertyListMutableContainers or NSPropertyListMutableContainersAndLeaves.
With the first all your containers (arrays and dictionaries that is) will be mutable. With the latter also the leaves (that is NSString and NSData objects) will be mutable.
Depending on how big your data set can get you probably should use a real database or Core Data instead.

NSUserDefaults never returns mutable objects.
Your code is performing every way of creating a mutable array you can think of (i.e. you're creating a mutable copy of something you just created a mutable copy of), but, you're only dealing with the root container item - not the inner / leaf items. So, when you do objectForKey:#"itemlar"] on your mutable array, you're getting an immutable object back.
To make it work, you'll need to write your own method that iterates and recurses through the array creating mutable copies at all levels.
Alternatively, you could look at a 3rd party option like this which digs under the hood of NSUserDefaults to generate mutable containers.

NSUserDefaults, and property lists in general, do not record mutability. When an object is re-created from the file it can be constructed either as a mutable or immutable object (for types which have the option, such as arrays). Unfortunately NSUserDefaults doesn't give you an API call to obtain an immutable object directly.
Two options you have are (a) create a mutable copy of the object returned by NSUserDefaults or (b) store the object yourself as a property list in a separate file - that way you can read it back as mutable directly.
For (b) read Apple's docs - it shows how mutability is handled.

You can directly do by using method insertObject.
In place of
[[[arrayTwo objectAtIndex:0] objectForKey:#"itemlar"] addObject:#"hop"];
use this,
[arrayTwo insertObject:#"hop" atIndex:0];
This will work for as i have tested it's also working finr after that you can make it as immutable object as NSARRAY and save it to NSUSERDEFAULTS.

Related

Changes in NSMutableDictionary not reflecting in parent NSDictionary

Question 1)
I am creating a NSMutableDictionary from a NSDictionary using the following code:
_allKeysDictionary = [receivedDictionary mutableCopy];
and I am updating the values from the _allKeysDictionary using the following code:
[_allKeysDictionary setObject:[textField text] forKey:#"field"];
But my parent NSDictionary that is receivedDictionary is not reflecting those changes made in _allKeysDictionary.
I need the values of receivedDictionary to be updated.
Question 2)
I am using
(__bridge CFMutableDictionaryRef)
to keep a pointer to one of the NSDictionary in my JSON response. but when I am trying to regain the above CFMutableDictionaryRef, I am still getting NSDictionary. I don't know what is wrong. I am using the following code to regain the Dictionary from the reference
NSMutableDictionary *getPointedDict = (__bridge NSMutableDictionary*) dataRefValue;
Q1: But the method mutableCopy even says so: A copy is created! The receivedDictionary logically won't be changed.
To update (after you're done):
receivedDictionary = _allKeysDictionary;
or to be safe that no changes can be made later:
receivedDictionary = [NSDictionary dictionaryWithDictionary: _allKeysDictionary];
By the way, you can write:
_allKeysDictionary[#"field"] = textField.text;
Q2: In Obj-C (and many other languages) casting does not change the structure of the object. If it's an NSDictionary, it will always stay an NSDictionary. So the actual cast will work (i.e. the compiler won't tell you), but once you start doing things with the object that are not implemented in the original class, your app will crash or you'll get other undefined results.
But my parent NSDictionary that is receivedDictionary is not reflecting those changes made in _allKeysDictionary
Of course they are not, you made a mutableCopy - that is a copy. You've now got two dictionaries with the same keys and values.
I need the values of receivedDictionary to be updated
If it is an NSDictionary you cannot do this, that is what immutable means. You can replace the reference stored in receivedDictionary to one which references your new mutable dictionary (or an immutable copy of it), but that doesn't do what you wish you have other variables storing references to the original dictionary.
However if the values in the dictionary are themselves mutable then you can alter those values. E.g. if you NSDictionary contains NSMutableArray values then you can change the elements of those arrays, but you cannot change which array is associated with which key in the dictionary.
Q2: You cannot simply cast a reference to an immutable dictionary to make it into a mutable one. Casting doesn't change the referenced object in anyway, it just changes the type the compiler treats it as (and if the type is not compatible with the actual type your program breaks).
It looks like you are unsure about objects, references and mutability; probably time to do some studying.
HTH
MutableCopy & copy both do deep copy on NSDictionary. The only difference is that mutableCopy makes your new dict mutable.
When you do deep copy, you are copying the value, not the reference, which mean whatever thing you do on your new dictionary, it won't affect the old value.
Plus, your original dict is immutable, even if you copy the reference, its value won't change.

Clear copied dictionary

Recently i created a post about clearing dictionary formed like key->value(NSArray).
I have 2 NSDictionary, first with data, second should contain all keys from first, but empty data for that key. Data will be added/removed later. This is how i create copy from main data dict (self.viewModel.releaseDict):
_releaseFormsDictCopy = [NSMutableDictionary dictionaryWithDictionary:self.viewModel.releaseDict];
When i checked, that objects (2 NSDictionaries) have different memory.
However, when i "clear" copy with method:
-(void)clearAllArraysInsideKeys{
for(id key in self) {
NSMutableArray *arr = [self objectForKey:key];
[arr removeAllObjects];
}
}
It appears that it flush all data from both dictionaries, not only copy. How to prevent clearing first NSDictionary?
Your dictionaries may be different instances, but their contents are still the same instances - you have created a shallow (mutable) copy. From your description what you want is a deep copy, where the dictionaries are different instances and each of the arrays they contain as the values are also different instances.
Simple option is to deep copy only that level. Create an empty NSMutableDictionary and then enumerate self.viewModel.releaseDict and add each key with a mutableCopy of the value.
This will be a 'deep-ish' copy of the dictionary, containing a 'shallow' copy of each array it contains.

Create a copy of a NSManagedObject

I need to temporarily store the content of a NSManagedObject into a dictionary. Because core data has its own memory management procedures, I don't want to keep any strong pointers to the NSManagedObject's fields, only the values are of interest at this point (values are passed between view controllers, the MOCs are different). I can't create weak pointers either because I want to control when the memory reclaim is done.
I tried a few things, all failed or did not fit the purpose.
a duplicate [[myNSMO alloc] initWithEntity:[NSEntityDescription entityForName:entity inManagedObjectContext:myNSMO.managedObjectContext] insertIntoManagedObjectContext:nil];
It's working, but does not fit into my app design (without getting into details)
generate a NSDictionary from the NSManagedObject, using [myNSMO dictionaryWithValuesForKeys:<#(NSArray *)#>]. That's not ok because it returns a dictionary with the addresses of the NSManagedObject fields.
create a NSDictionary populating each key-value using a copyWithZone, like this
[myDictionary setObject:[myNSMO.field copyWithZone:nil] forKey:#"Key"];
Doesn't work either, I still get the field address...
Manually enter each field with
[myDictionary setObject:[NSString stringWithFormat:#"%#",myNSMO.field ] forKey:#"Key"];
It's fine this time, I do get new memory allocation. But that's highly time consuming to code this manually...
Any chance that someone found clever way to do that? the reason option 1) did not work is because I use the dictionary as a queue. I first store a copy of the object, then pop the entry out when required. A copy of that particular dictionary entry is then returned to the asking method. The problem is that I can't create a copy of an NSManagedObject that was created using [[...] insertIntoManagedObjectContext:nil];
Any solutions?
It's safe to keep strong pointers to the fields of a managed object in most senses — relationships are special but the actual Foundation objects of dates, strings and numbers are ordinary objects that'll stay in memory if you have a strong reference.
That being said, to create a dictionary copy containing all the properties of an entity you could do something like:
NSArray *properties = [[object entity] properties];
NSMutableDictionary *dictionaryRepresentation = [NSMutableDictionary dictionary];
for(NSAttributeDescription *attribute in properties)
{
// we want only actual attributes, not relationships
// or fetched properties
if([attribute isKindOfClass:[NSAttributeDescription class]])
{
[dictionaryRepresentation
setObject:[object valueForKey:attribute.name]
forKey:attribute.name];
}
}
So you're using the fact that managed objects expose a description of their entities which includes a list of properties, whittling those properties down to just the attributes, then using key-value coding to fetch the current value of each property and finally inserting it into the dictionary.
If for some reason you did want copies of the properties — though, as I say, there's absolutely no reason to do so — you'd copy (and autorelease if you're not using ARC) each property when inserting it into the dictionary.

Store an array of UIViews in NSUserDefaults

I'm trying to add an array of uiviews to NSDefault but it doesn't seem to be keep the array. Does any one know why? I also tried to store each view in nsvalue before storing it in nsdefault which still didn't work.
NSArray *arr = [[NSArray alloc] initWithObjects:[NSValue valueWithNonretainedObject:myView], nil]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arr forKey:#"myKey"];
NSArray *resultArray = [defaults objectForKey:#"myKey"];
and resultArray is nil!
Thanks
the reason why I'm trying to do this is because these are the header views of my uitableview. Since it takes time to create them I wanted to create them only once and store them for future access.
From the docs for NSUserDefaults:
The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. 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. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.
If you want to put a UIView (why?) in NSUserDefaults, you need to archive it first into an NSData object.
But you need to ask yourself why you want to put a view in NSUserDefaults. You should only be putting bits of data in NSUserDefaults. Views display data. It's easy to redisplay a view once you have the data back. Consider just putting some needed data in NSUserDefaults.
Are you sure you want to do that? It is definitely better to store an array of models to the data base or some file and recreate views from them when needed.
A ha! You are not the first person to face this issue. I've not had this type of issue myself but, in the link below, is a blog with code that allows you to cache and re-use your views. Then you would only need to re-create the views when you launch. Example code:
Cache UIViews for re-use in tableview

Add objects to dictionary created by JSONKit?

In my project I have to load a number of json files. I parse them with JSONKit and after every single parsing with
NSMutableDictionary *json = [myJSON objectFromJSONString];
I add them to an array like:
[self.themeArray addObject:json];
This works fine so far. Now I need to pass the dictionaries arround between views. Works so far as well, but I need to add few more objects to the dictionary object-> json. Even it I declared json as NSMutableDictionary it does not allow me to add objects as it seems the JSONKit parser creates non-mutable dictionaries.
I was thinking about creating an object which contains the json dictionary and my additional data side by side so I wouldn´t have to change the json dictionary. I could even change it to NSDictionary because there is no need to change it. But that seems somehow not-elegant to me.
Do you have any idea how I can solve this issue without changing the JSONKit lib?
Thanks in advance!
EDIT
i just tried after changing my code to
NSMutableDictionary *json = [[myJSON objectFromJSONString] mutableCopy];
something like this
[[self.theme objectForKey:#"theme"] setObject:sender forKey:#"sender"];
[[self.theme objectForKey:#"theme"] setValue:sender forKey:#"sender"];
Xcode throws an exception:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '* -[JKDictionary setObject:forKey:]: mutating method sent to immutable object'
I assume that´s due to the fact there are still nested dictionaries in the superior dictionary. Then i would have to interate through my json object to copy all dictionaries to mutable dictionaries, right?
Perhaps it's better to switch to NSJSONSerialization as suggested by Guillaume.
EDIT
I just tried something like this
[self.theme setValue:sender forKey:#"sender"];
And it works now! It was as i assumend. Only the json object was copied to a mutable object. Probably obvious to you, it was not to me.
Thank you all for your help!
EDIT
Finally i changed my code again after i could not manage to change all objects deep inside my dictionary data to mutable objects. I threw out JSONKit and use now NSJSONDeserialization as recommendet here with the option NSJSONReadingMutableContainers. My code looks now like this and all containers (arrays and dictionaries) are mutable deep inside too. That makes me happy! ;-)
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:myJSON options:NSJSONReadingMutableContainers error:&jsonParsingError];
You can always create mutable versions of objects from their non-mutable counterparts by copying them.
NSMutableDictionary* json = [[myJSON objectFromJSONString] mutableCopy];
It is not optimal, but copying smaller dictionaries does is usually not noticable from a performance point of view.
Even it I declared json as NSMutableDictionary it does not allow me to add objects as it seems the JSONKit parser creates non-mutable dictionaries.
What type the variable is declared at means nothing. You could have declared json as NSNumber and that wouldn't make it an NSNumber.
You need to make a mutable copy of the dictionary (with mutableCopy) to get an NSMutableDictionary.
I have three ideas for your.
Create real data model objects and store them in your array. Use the JSON dictionary to init your object.
Store NSMutableDictionary objects in your array. Pass the JSON dictionary to +[NSMutableDictionary dictionaryWithDictionary:] to init the NSMutableDictionary. Others have suggested calling -[NSDictionary mutableCopy] on the JSON dictionary to do the same thing.
Create a category based on NSDictionary that stores the additional data.
NOTES:
Generally creating classes to represent your data is considered the best option, but it is also the most amount of up front work. Basically you are trading more up front work against more maintenance work as you try to keep up maintaining the dictionaries.
Storing mutable dictionary is exactly what you seem to be asking for, but it may be lots of works to find all the places where JSON dictionaries are added to the array and replacing them with the new call.
Creating a category for NSDictionary means you shouldn't need to change any of your current code, but it requires maintainers to understand how you have enhanced NSDictionary. In addition, it will help separate your changes from the original parsed JSON. You can use associated objects to store the data.

Resources