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.
Related
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.
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]].
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.
I am reading on objective-c (a nerd ranch book), and I can't help thinking about this question: How do I decide which collection type, NSArray or NSDictionary (both with or w/o their mutable subclasses), to use when reading content from URL?
Let's say am reading JSON data from a PHP script (a scenario am dealing with), which to use? I know it is stated in many references that it depends on structure of data (i.e. JSON), but could a clear outline of the two structures be outlined?
Thank you all for helping :)
NSArray is basically just an ordered collection of objects, which can be accessed by index.
NSDictionary provides access to its objects by key(typically NSStrings, but could be any object type like hash table).
To generate an object graph from a JSON string loaded via a URL, you use NSJSONSerialization, which generates an Objective-C object structure. The resulting object depends on the JSON string. If the top-level element in your JSON is an array (starts with "["), you'll get an NSArray. If the top-level element is a JSON object (starts with "{"), you'll get an NSDictionary.
You want to use NSArray when ever you have a collection of the same type of objects, and NSDictionary when you have attributes on an object.
If you have, lets say a person object containing a name, a phone number and an email you would put it in a dictionary.
Doing so allows the order of the values to be random, and gives you a more reliable code.
If you want to have more then one person you can then put the person objects in an array.
Doing so allow you to iterate the user objects.
"withContentOfURL" or "withContentOfFile" requires the data in the URL or the file to be in a specific format as it is required by Cocoa. JSON is not that format. You can only use these methods if you wrote the data to the file or the URL yourself in the first place, with the same data. If you write an NSArray, you can read an NSArray. If you write an NSDictionary, you can read an NSDictionary. Everything else will fail.
I have a large number of nested dictionaries and the leaf (or most nested) dictionaries store integer data and integer keys. All the information remains constant (but may change in a future release). I am currently allocating the dictionaries from constants in code but I feel I should be reading that information from XML or similar. I have read about Core information, plists, databases and archives but I don't want the user to be able to change it, I never want to be able to write it (except maybe during the release procedure) and I never want to display it. I would like to be able to hand edit it before release.
What is the best method to store this constant data?
Basically you need to ship your data in files with the app -
XML or JSON are both suitable for this. When I have had to do something similar I used JSON
It works something like this :
Define your JSON in text file (UTF8) and then use the
NSString initWithContentsOfFile to load file contents into a NSString
You can then use the NSJSONSerialization JSONObjectWithData to give you the top level dictionary for your JSON
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
From this you can extract your NSStrings / NSArrays using NSDictionary objectForKey for your data. Obviously the exact format will depend on your JSON format