Changes in NSMutableDictionary not reflecting in parent NSDictionary - ios

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.

Related

How to maintain the order of key added in NSMutableDictionary

I didn't knew this at first place, I thought that the key/value pair I am adding to my dictionary will be in the same order when I try to retrieve it back...
Now here is my question -
I have a ViewController which I have made as singleton, inside this VC I have defined:
#property (nonatomic) NSMutableDictionary *dictionary;
Now I try accessing this dictionary from various other classes and set its contents via:
[[[ViewController sharedViewController] dictionary] setValue:[NSNumber numberWithBOOL:NO] forKey:#"xx"] , yy ,zz and so on
I have my delegates implemented which would hit for a particular key(xx,yy,zz and so on). Now whenever a particular delegate method is hit I need to update my dictionary with same key but [NSNumber numberWithBOOL:YES] which is happening .. but the order in which I added the items in dictionary is not maintained ... How can I achieve this?? I need to maintain the order in the same way in which I have added my items to the dictionary at first place??
Can someone please help me out??
As pointed, you should use NSArray to have your values ordered. You can also use some 3rd party APIs like: M13OrderedDictionary or others, however, that's not a pretty solution.
Obviously, the desired solution is to create your own object or struct and keep an array of those objects/structs.
NSDictionary is just a mapping between keys and values that has no defined order. If you try to iterate over the keys, you may or may not get them back in the same order you added them, and you should never depend on the ordering of the keys when iterating over them.
One thing you could do is create an NSArray that contains the keys in the order you want them. Then you can iterate over the keys in the array and get the values from the NSDictionary in the order you wanted. The combination of these two basically gives you a sorted key NSDictionary.
Another thing you could do is to just use an NSArray to stores the values, unless the keys that you're using matter as well. But if all you're trying to do is get the values in a certain order, then I would say NSArray should work fine.
You can make a copy of key by using the following code:
NSArray *allKeys = [dictionary allKeys];
Then, the keys all saved in order and you can access particular value by getting specific key in allKeys array and retrieving it by using dictionary[allKeys[2]].

NSMutableDictionary contents inconsistent with output of allValues

So long story short, there's a discrepancy between the output of a NSMutableDictionary's contents and the result of calling allValues on the same object. Below is some debugger output after inspecting the object which demonstrates my problem: (made generic of course)
(lldb) po self.someDict.allKeys
<__NSArrayI 0xa5a2e00>(
<SomeObject: 0xa5a2dc0>,
<SomeObject: 0xa5a2de0>
)
(lldb) po self.someDict.allValues
<__NSArrayI 0xa895ca0>(
0.5,
0.5
)
(lldb) po self.someDict
{
"<SomeObject: 0xa5a2dc0>" = (null);
"<SomeObject: 0xa5a2de0>" = (null);
}
So as we can see, the actual output of the NSMutableDictionary contains null values for both its entries, but the contents of .allValues contains the proper data. These three outputs were taken at the same time in execution.
I'm not sure why this is happening, but I think it may have something to do with the fact that I'm encoding/decoding the object which this dictionary is a property of using CoreData. I believe I'm doing this properly:
[aCoder encodeObject:self.someDict forKey:#"someDict"];
and to decode
self.someDict = [aDecoder decodeObjectForKey:#"someDict"];
The weird thing is that if I inspect the dictionary before it ever gets encoded, it is still in the state described at the beginning of the post, so this is why I'm doubtful the CoreData actions are screwing with the contents.
As always, please don't hesitate to request additional information.
EDIT: The problem was as answered below. I was using a custom class which didn't cooperate with isEqual, so my solution was to change the storage and structure of my logic, which made using a Dictionary unnecessary.
I have not been able to duplicate the problem using NSString as keys and NSNumber as values. I suspect that your custom class does not properly implement hash and/or isEqual. Specifically, the results from those two methods must be consistent, meaning that if isEqual returns true, then the hash values for the two objects must be identical.
You also need to ensure that your class implements NSCopying properly and that a copy is equal to the original.
As a general rule, don't use custom objects for dictionary keys. Just use strings and be done with it.
As user3386109 points out, custom objects must properly implement the -hash and -isEqual methods in order to be used as dictionary keys, and even then, custom objects don't work correctly for dictionary keys for things like key/value coding.

Mutable Objects inside NSUserDefaults

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.

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.

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