iPhone - Changing a sub-sub-sub NSMutableDictionary value - iphone

If I have a data tree that is something like :
NSMutableDictionary (dict1)
NSMutableDictionary (dict2)
NSMutableArray (array)
NSMutableDictionary (dict3)
Key1
Key2
NSMutableDictionary (dict_n)
Keyn
Keyn
NSMutableDictionary (dict_n)
NSMutableArray (array_n)
NSMutableDictionary (dict_n)
Keyn
Keyn
NSMutableDictionary (dict_n)
Keyn
Keyn
If I want to change the value of Key1, is there a simplier way than...
getting dict1
then getting dict2
then getting array
then getting dict3
converting dict3 to a mutable Dictionary
then setting key1
Converting array to a mutable array
then setting dict3 into array
converting dict2 to a mutable Dictionary
then setting array into dict2
converting dict1 to a mutable Dictionary
then setting dict2 into dict1
Doing that for each value I have to change is a real headache, and really code consuming.

You can't send a message to an object unless you have a pointer to that object, so in a basic sense the answer to your question is no, there's no other way.
However, one presumes that this data structure that you have represents some sort of data model. As such, it should probably be contained in some sort of model class that understands its parts, and that class should be the only one that needs to understand how the data is stored. The model class should offer a higher-level interface to the data. Say dict3 represents one particular vehicle in a fleet, and the keys are things like "vehicleTag", "registrationDate", "purchaseDate", etc. Maybe the dictionaries at the dict2 level the fleets in different regions, and dict2 itself represents the northeast fleet. Then the VehiclePool class, your model class which stores all the data, might offer methods like:
-registrationDateForVehicle:(int)vehicleIndex inFleet:(NSString*)fleetKey;
-setRegistrationDate:(NSDate*)regDate forVehicle:(int)vehicleIndex inFleet:(NSString*)fleetKey;
I'm not sure I'd really want an API like that -- I'd prefer to get the list of vehicles for a given fleet and then operate on those with simpler accessors, but you seem to want to avoid several levels of accessors. The point here is that you shouldn't be writing a ton of code to do the operations you need; you should write methods that know how to access the data and then call those.

The NSDictionary documentation states:
In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see “Key-Value Coding Fundamentals”).
Therefore, if your keys (and sub-keys) are all strings, you can do the following to retrieve and set values:
id myNestedObject = [topLevel valueForKeyPath:#"firstKey.secondKey.thirdKey"];
[topLevel setObject:newNestedObject forKeyPath:#"firstKey.secondKey.thirdKey"];

Related

Accessing array/set of objects with keys

I want to be able to add objects to an NSArray and access them with Keys. Currently the way im doing it is creating a seperate NSDictionary of key-value pairs where the value is an integer number representing the index in my NSArray. This seems like an extra step to me.
If my understanding of NSDictionary is correct, only 'values' can be stored: a pointer to an object cannot.
Surely there must be an equivalent NSDictionary type function that allows objects to be stored and accessed with a key? I have looked through the documentation, but cant seem to find any answers, unless im missing something obvious.
NSDictionary is to store key value pairs. if you are adding key value pair after you created the dictioanry, use NSMutableDictionary class . example,
[dictionaryObject setObject:#"" forKey:#"abc"];
You can store objects in NSDictionary and can be accessed via keys...
In short, no.
An array (NSArray) is an ordered collection of references to objects, so simply said, an ordered collection of objects.
As opposed to dictionaries, which are unordered and values are accessed by keys.
You understanding of collections is probably wrong, you don't store values, but pointers (references).
The extra step is necessary if you need to store the references in an array, but in this case, you should consider using a dictionary. An option is to use keys that take care of the order.
For example :
[myDictionary objectForKey:#"1"];
could be an equivalent of :
[myArray objectAtIndex:1];
Thats wrong, you can store objects in a NSDictionary. Look at the method dictionaryWithObjects:forKeys: or dictionaryWithObjectsAndKeys:
I have no experience in Cocoa but looking at the documentation it seems like NSDictionary (or at least NSMutableDictionary) should handle your request (without you using NSArray).
I think I understand your problem. My suggestion for you is to use NSMutableArray and macros, like:
NSMutableArray *array=[[NSMutableArray alloc]init];
#define SOME_MACRO 0
id someObject;
[array insertObject:someObject atIndex:SOME_MACRO];
id getterObject=[array objectAtIndex:SOME_MACRO];
Of course define the macros in the header file.

Using NSDictionaries

I have a number of NSString objects I want to save into an NSDictionary.
How is an NSDictionary initialized with the keys and do the values need to be set there and then or can the dictionary be setup using just the keys and the objects later set?
To start with here's a link to the NSDictionary documentation, and NSMutableDictionary
You can create a NSMutableDictionary with just keys by passing [NSNull null] as the object for that key. It's important to use a mutable dictionary here otherwise you won't be able to change the dictionary after you've created it, and a dictionary that just has keys instead of objects is of little use.
That is what NSNull is for: to provide null values for collection types that don't allow nils.
A dictionary can be initialized both as empty or as a list of (value,key) pairs.
Initializing the dictionary just with keys and not values is useless/meaningless in Objective-C, since it will be equivalent to a void initialization.
If you want to create a dictionary and want to be able to set objects later, you have to use a NSMutableDictionary, that has not a static initialization of its data, through its setObject:forKey: method.

Do I need to initialize an iOS empty nested array that's part of a plist import?

the code below is working, but I want to make sure it's correct. I'm nervous about having an empty Array inside my dictionary that I create from the plist, since typically it seems that if you don't, say, initWithCapacity:1 then you often get memory errors once you start trying to add items.
At least, that's been my experience with NSMutableDictionary. However, this is the first time I'm trying to implement nested data objects, so perhaps the reason this code works is that the nested array is automatically initialized when it's imported as part of its parent dictionary?
Any and all comments appreciated. Thanks.
First, here's what the plist looks like that I'm using to create my dictionary:
Next, here's my code where I'm using the plist to create a dictionary, then adding an item to dataArray
// Create a pointer to a dictionary
NSMutableDictionary *dictionary;
// Read "SomeData.plist" from application bundle
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"SomeData.plist"];
dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
// Now let's see if we can successfully add an item to the end of this empty nested array. How 'bout the number 23
NSNumber *yetAnotherNumber = [NSNumber numberWithInt:23];
[[dictionary objectForKey:#"dataArray"] addObject:yetAnotherNumber];
// Dump the contents of the dictionary to the console
NSLog(#"%#", dictionary);
Okay, fine, simple, good. When I Log the dictionary contents it shows that "23" has been added as an array value to dataArray. So the code works. But again, I want to confirm that I'm not "getting lucky" here, with my code just happening to work even though I'm not properly initializing that nested array. If so, then I could run into unanticipated errors later on.
So to sum up, dataArray is an empty array inside the .plist, so do I need to initialize it somehow (using, for example initWithCapacity: or something else) before I can properly populate it, or is the way I'm coding here just fine?
Thanks again.
EDIT
Hey all. I've been doing continued research on this, in the interests of finding a satisfying answer. I think I may have stumbled upon something, via this link on deep copying. His previous posts on deep copying had presented some code to do essentially what I was looking for above: create a mutable copy of a dictionary or array, from a plist, that also has mutable sub-structures.
However, as mentioned in the link above, it looks like these methods were superfluous, due to the CFPropertyListCreateDeepCopy method, which can be invoked with a call such as
testData = CFPropertyListCreateDeepCopy(kCFAllocatorDefault, [NSDictionary dictionaryWithContentsOfFile:path], kCFPropertyListMutableContainersAndLeaves);
So, my question is, can I properly use CFPropertyListCreateDeepCopy, in the way shown, to achieve what I've been asking about here? In other words, can I use this method to import my dictionary from a plist with fully mutable, nested data objects?
As I mentioned in one of the comments, I know I can create a nested, mutable dictionary manually, but for complex data that's just not practical, and it seems unlikely that built-in methods to import a mutable plist don't exist. So, based on the above, it looks like I've possibly found the solution, but I'm still too new to this to be able to say for sure. Please advise.
(Side note: I would simply test the code, but as we've established, the current SDK is buggy with regard to allow you to edit immutable nested dictionaries, contrary to the documented behavior. So as before, I'm not just interested in whether this works, but whether it's correct)
Thanks in advance.
init... methods should only be called once, immediately after a call to alloc or allocWithZone:. When framework code creates and returns an object or graph of objects, their init... methods have already been called, so sending another init... message would have undefined results. Don't do that.
Interestingly, in spite of what the documentation appears to say (and admittedly I probably missed a key sentence or paragraph somewhere), when you create an instance of a mutable collection by reading a plist, any nested collections are also mutable. I ran the following little experiment in a test harness just to be sure:
NSMutableDictionary *pets = [NSMutableDictionary dictionaryWithContentsOfFile:#"/tmp/Pets.plist"];
NSMutableArray *cats = [pets objectForKey:#"cats"];
[cats addObject:#"Foo"]; // EDIT: Added line I accidentally omitted earlier
NSLog(#"%#", cats);
So again, the nested collections created when you read in the plist are fully initialized, and mutable to boot, so you can simply use them, as you've been doing.
EDIT
However, after doing some further reading of the docs, I think the OP is right to feel uneasy about relying on what is apparently an undocumented feature of the current version of the SDK. For example, the Property List Programming Guide states:
If you load the property list with
this call:
NSMutableArray * ma = [NSMutableArray arrayWithContentsOfFile:xmlFile];
ma is a mutable array with immutable
dictionaries in each element. Each key
and each value in each dictionary are
immutable.
So, to be on the safe side, if you need a nested collection to be mutable, you should create it yourself. For example, I'd recommend rewriting the code in the example above as follows:
NSMutableDictionary *pets = [NSMutableDictionary dictionaryWithContentsOfFile:#"/tmp/Pets.plist"];
NSArray *cats = [pets objectForKey:#"cats"];
NSMutableArray *mutableCats = [cats mutableCopy];
[pets setObject:mutableCats forKey:cats];
[mutableCats release];
You can then safely make changes to the nested mutable collection:
[mutableCats addObject:#"Foo"];
Any object in a dictionary which is created by reading from disk will be properly initialized. You will not have to do it on your own. However, as pointed out by jlehr, contents of the dictionary should be immutable. If you want the contents of the dictionary to be mutable, you will need to change them on your own. I have no idea why your program is not throwing an exception.
I do not know why you are getting memory errors while not using initWithCapacity:1 in other situations. The following code is perfectly valid:
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:#"object1"];
[array addObject:#"object2"];
NSLog(#"%#",array);
[array release];
If you don't specify a capacity, the array won't pre-allocate any memory, but it will allocate memory as required later.
Edit:
It is perfectly acceptable to use NSDictionary with CFPropertyListCreateDeepCopy. In Core Foundation, a CFPropertyList can be a CFDictionary, CFArray, CFNumber, CFString, or CFData. Since NSDictionary is toll-free bridged to CFDictionary, you can use it wherever a CFDictionary is asked for by casting, and vice-versa. Your code as is will give a warning, but you can suppress it by casting the dictionary and return values.
NSDictionary *testData = (NSDictionary*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)[NSDictionary dictionaryWithContentsOfFile:path], kCFPropertyListMutableContainersAndLeaves);

problem in nsuserdefaults

hii every one i have stil problem in nsuser defaults i'll tell the scenerio in detail
First i have diclared nsmutable array in appDelegate and set it in NSUserDefaults With For Key#"abc"
In FirstView Controller i first fetch the array from NSUserDefaults and save its values in NSMutable Array
When a Click say abcButton i have create a dictionary and adding values in it like
[abcDictionar setObject:[[abcMutableArray objectAtIndex:indexPath.row] objectForKey:#"abc"] forKey:#"abc"];
When i added all values in NSDictionary Then i add NSDictionary in NSMutable Array
like This
[abcMutableArray addObject:abcDictionary];
Then i save it NSUserDefaults
It Give me Exception in Point 4
When i add nsdictionary in Point One It All work fine but data in array is ambigous and it raise exception when am going to display it in tableview
if any one has some idea then let me know thanks in advance...:)
NSUserDefaults does not store mutable objects, only immutable ones. When you retrieve objects from it you must cast/copy them into mutable objects if you wish to mutate them.
Also be aware that:
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.
Which is from the NSUserDefaults documentation.

How to get good grip on NSMutableDictionary, NSEnumerator, NSMutableSet?

I am little bit backward in knowledge on these three topics: NSMutableDictionary, NSEnumerator, NSMutableSet. When I want to use them, it feels very hard, even when I've gone through the developer documentation.
Is there any sample code to understand it clearly for all three topics?
Please help me.
Thank you,
Madan Mohan.
The best way to understand these depends on what your prior experience is. NSDictionary is exactly what it sounds like: a dictionary. What that means is that given a key (or a headword, as in a dictionary), you can look up a value (or definition):
For instance, this dictionary gives information about my dog:
KEY VALUE
-------------------------------------------
#"name" #"tucker"
#"species" #"canis lupus familiaris"
#"favorite" #"biscuits"
With a dictionary dogInfo containing that information, we could send [dogInfo objectForKey:#"name"] and expect to receive #"tucker".
The difference between NSDictionary and NSMutableDictionary is that the latter allows changes after initialization. This lets you do things like [dogInfo setObject:#"fetch" forKey:#"game"]. This is helpful for maintaining state, memoizing referentially transparent requests, etc.
NSSet is a way to have a bunch of objects, with a few important bits: there is no defined order to those objects, and there can only be one of each object (no duplicates). Use NSSet for when you need to contain unique, unordered objects. NSMutableSet is the variant of NSSet which allows for changes (such as adding or removing objects) after initialization.
NSEnumerator is a bit more complicated, but you usually won't need to deal with it unless you are writing your own libraries, are coding archaically, or are doing complex enumerations. Subclasses of NSEnumerator are used by collection classes, such as NSDictionary, NSArray, and NSSet, to allow their objects to be enumerated. Usually, you'd just enumerate over them using a foreach-loop, since they all implement <NSFastEnumeration>. But sometimes, you'll want to do more specific things, like enumerate over the objects (instead of the keys) of a dictionary, or enumerate over an array in reverse. This is where instances of NSEnumerator (usually defined as properties on your collection objects) will become helpful.
Update
Justin in the comments pointed out that NSEnumerator conforms to <NSFastEnumeration>; that means, the chances are next-to-nothing that you'll need to know how to use an NSEnumerator; you can just do a foreach loop over the enumerator itself, like so:
for (id object in [dogDict objectEnumerator]) {
// doing something with the object, disregarding its key
}