Looping through values in NSDictionary throws fault - iphone

I have a plist file that I am loading into an NSDictionary *setDictionary that contains a set of fields, pictureDesc1, pictureDesc2, etc.
Once the NSDictionary is loaded, I can retrieve a value using
[setDictionary objectForKey:#"pictureDesc1"];
But I cannot do a loop like this:
for (int i=1; i<=numberOfPictures; i++) {
NSString *keyName = [NSString stringWithFormat:#"pictureDesc%d",i];
NSString *description = [NSString stringWithFormat:#"%#", [setDictionary objectForKey:keyName]];
}
Is there a different way to dynamically call keys from within an NSDictionary?

If you keys fit a numerical pattern, then it would be easier and more robust to simply store them in a array. You could even store an array as a value in the dictionary with the key of "pictureDescription".
Then when you wanted to loop through them just use a simple numerical loop:
NSArray *pictArray=[setDictionary valueForKey:#"pictureDescription"];
NSString *description;
for (i=0;i<[pictArray count];i++){
description=[pictArray objectAtIndex:i];
//... do whatever
}
If you find yourself shoehorning the functionality of an array into a dictionary or vice versa you probably should back out and just use an array or dictionary in the first place. When using a dictionary, just use an enumerator to step through the values.

Related

Sorting NSMutableDictionary's data

I am having an NSMutableDictionary with, being filled dynamically. It looks like this:
{
SomeKey = 6;
AnotherKey = 2;
JustAnotherKey = 28;
}
I need to sort this, so it will be like this one:
{
JustAnotherKey = 28;
SomeKey = 6;
AnotherKey = 2;
}
Is there any way to achieve this? Thanks in advance.
No, sorry!
An NSDictionary doesn't support sorting it's keys - you would have to do that yourself.
Get the keys array from your dictionary, sort that and then go through and get the values from your dictionary. Something like :
NSArray *keys = [myDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:#selector(compare:)];
NSArray *values = [NSMutableArray array];
for (id key in sortedKeys)
[values addObject:[myDictionary objectforKey:key]];
Now, values are in the correct order.
However, that's quite a lot of work; if you want them sorted, I would look at storing them in an array to start with?
A Dictionary is an unordered set, which means it doesn't have any order of its elements.So even if you insert the first object as say "one":"first value", and then "two":"second value", when you iterate over the keys, you might get it in any random order(eg: "two' and then "one").
However, if all you want is the values in sorted order, you can iterate over all the keys, fetch the values and store it in an array, and then sort them.
NSArray *values=[myDict allValues];
NSMutableArray *sortedKeys=[[NSMutableArray alloc] init];
NSArray *sortedValues = [values sortedArrayUsingSelector:#selector(yourSelector)];
for (val in sortedArray){
NSString *key=(NSString*)[[myDict allKeysForObject:val] objectAtIndex:0];
[sortedKeys addObject:key]
}
This would be starter for getting first the values in sorted order, and then the corresponding keys. (It is not doing any error checks. So beware of OutOfIndex exceptions).
I am not sure how good would be the efficiency of this code be, coz allKeysForObject would be iterating over all the keys.
Instead of using a NSMutableDictionary, you might consider to use a NSMutableArray and populate it with your own model class which contains a property with the key string and a property with the value.
NSMutableArray provides methods to sort these objects.
Is this helpful enough?

How to parse a Dictionary according to its index?

I have a dictionary and i want to parse the dictionary according to the index of the keys inside dictionary.Actually i want to switch to different dictionaries as per the value of current variable which mean i want to keep accessing the object inside my dictionary according to the index.
k = k+1;
NSDictionary * checkBox = [step objectForKey:#"CheckBoxSingle"];
NSDictionary * first = [checkBox objectAtIndex:k];
Thanks
Here you have a couple of examples to iterate through an nsdictionary. Using his first example, you can access arbitery values using the array from [checkBox allKeys];. Not that you should do it using an NSDictionary because the order of stuff AFAIK can be completley random. You can look into sorting an NSArray though if it will serve your purpose.
Also NSDictionary implements NSFastEnumeration, which means that if you want you can do;
for (NSString *currentKey in checkBox)
{
NSDictionary *current = [checkBox objectForKey:currentKey];
}
Use a for loop
int k;
for (k=0;k<LIMIT;k++) { //change LIMIT to number of times to loop.
NSDictionary * checkBox = [step objectForKey:#"CheckBoxSingle"];
//NSDictionary doesn't respond to objectAtIndex:
//do something...
}

How to add the static data into the Dynamic array in iPhone?

I want to add the static contents into the Mutable Array. I have parsed the data using XML parsing and stored the dynamic data into the mutable array. Now i want to add the static string into that Mutable Array. So how can i add that?
For Eg:
In my dynamic Array of content is,
{
first,
third,
fourth,
fifth.
}
I want to add the static String into the 1st index of array. Because my requirement is, displayed the static content into the 1st position.
Expected output:
{
first,
second, //Add the static data into the First index of Array
third,
fourth,
fifth.
}
So how can i do this?
Thanks.
If I understand what you mean. You can use:
[NSMutableArray insertObject:atIndex:]
Supposing myArray is the instance of NSMutableArray:
[myArray insertObject:#"second" atIndex:1];
instead of NSString you can insert every object you want.
After creating NSMutableArray from XML parsing you can implement like this,
suppoose In XMLArray you having your xml data now you want to insert static date at any location,
NSMutableArray *tempArray=[NSMutable array];
for(int i=0;i<[XMLArray count];i++)
{
if(i==1)//accrding to you
[tempArray addObject:yourStaticData];//yourStaticData is object having your data.
else
[tempArray addObject:[XMLArray objectAtIndex:i]];
}
//use tempArray according to you.

How do I copy individual Nested NSDictionary's from a NSDictionary to a temporary NSMutableDictionary

Ok so I want to create a temporary NSDictionary from a NSDictionary of nested dictionaries, but I want to deep copy individual items(dictionaries) from the top level dictionary.
The end result is to have a filtered dictionary that i can process and discard without effecting the main dictionary.
That sounds really confusing, so how about a little code to show you what I mean, heres the function i'm working on, this is a rough coding layout, but basically complete in its path of process.
I've looked at reference books and various samples online with no joy.
Cheers,
Darren
- (void)setPricingData
{
// get selected lens option
NSDictionary *aOption = [self.lensOptionsDict objectAtIndex:self._lensOptionsIndex];
if ( aOption == nil )
return;
// get selected lens type
NSDictionary *aType = [self.lensTypesDict objectAtIndex:self._lensTypesIndex];
if ( aType == nil )
return;
// get lens option id and variation_id
NSString *option_id = [aOption valueForKey:#"id"];
NSString *option_variation_id = [aOption valueForKey:#"variation_id"];
// create temp dictionary for type pricing selection
int count = [self.lensTypesDict count];
NSMutableDictionary *aPrices = [[NSMutableDictionary alloc] initWithCapacity:count];
// cycle prices for option id and variation_id matches
for ( NSDictionary *item in self.pricesDict )
{
NSString *variation_id = [item valueForKey:#"variation_id"];
NSString *value_id = [item valueForKey:#"value_id"];
// add matches to temp dictionary
if ( [option_variation_id isEqualToString: variation_id] )
{
if ( [option_id isEqualToString: value_id] )
[aPrices addObject: item];
}
}
// get price from temp dictionary for selected lens type index
NSDictionary *price = [aPrices objectAtIndex:self._lensTypesIndex];
if ( price != nil )
{
// assign values to outlet
self.priceAndStockId = [price valueForKey:#"price"];
self.priceSelected = [price valueForKey:#"price"];
}
// release temp dictionary
[aPrices release];
}
It looks like you're mixing up dictionaries with arrays.
Arrays respond to objectAtIndex whereas dictionaries respond to objectForKeys. Remember that an array is a set of cells that you can index into, starting from 0 all the way up to [array count] - 1.
A dictionary is similar to an array, except that a hash function is used as the indexing method. This means that you need a key to get, or set, and object.
Setting an object in an NSMutableDictionary
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
[myDictionary setObject:anObject forKey:aKey];
Or, you can have an array of keys and corresponding array of objects, and do:
NSDictionary *completeDictionary;
completeDictionary = [NSDictionary dictionaryWithObjects:objectArray
forkeys:keyArray count:[keyArray count]];
In either case, you must have keys for objects. This is in contrast to a regular array in which you can simply do
[myArray addObject:myObject];
To get objects from a dictionary, do
myObject = [myDictionary objectForKey:key];
To get objects from an array, do
myObject = [myArray objectAtIndex:anIntegerIndex];
Finally, your original question pertained to deep copying. To have your dictionary keep an object that won't change, ie, a deep copy, you can do the following:
Assuming I want to store a dictionary within a dictionary, and I have an associated key for the top-level dictionary, I can do the following:
I have an NSMutableDictionary, called topLevelDictionary
I have an NSDictionary, called dictionaryTwo
I have an NSString, which is my key, called myKey.
To make a deep copy of dictionaryTwo, I can do
// assuming topLevelDictionary is previously defined
[topLevelDictionary setObject:[[dictionaryTwo copy] autorelease] forKey:myKey];
In this manner topLevelDictionary will contain a copy of dictionaryTwo whereby if dictionaryTwo changes, the object in topLevelDictionary will not.

How can i get Original order of NSDictionary/NSMutableDictionary?

i have created NSMutableDictionary with 10 keys.Now i want to access NSMutableDictionary keys in a same order as it was added to NSMutableDictionary (using SetValue:* forKey:* );
How can i achieve that ?
If you absolutely must use a dictionary container, you have to use a key that is sortable by the order in which you add key-value pairs. Thus, when creating your dictionary, you use a key that is an auto-incrementing integer or similar. You can then sort on the (integer) keys and retrieve the values associated with those keys.
If you do all of that, however, you may as well just use an NSMutableArray and add values to the array directly! It will be much faster and require less code. You just retrieve objects in order:
for (id obj in myArray) { /* do stuff with obj... */ }
NSMutableDictionary can't do that. Take a look at e.g. Matt Gallaghers OrderedDictionary.
I wrote a quick method to take a source array (of objects that are all out of order) and a reference array (that has objects in a desired (and totally arbitrary) order), and returns an array where the items of the source array have been reorganized to match the reference array.
- (NSArray *) reorderArray:(NSArray *)sourceArray toArray:(NSArray *)referenceArray
{
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [referenceArray count]; i++)
{
if ([sourceArray containsObject:[referenceArray objectAtIndex:i]])
{
[returnArray addObject:[arrReference objectAtIndex:i]];
}
}
return [returnArray copy];
}
Note that this is very fragile. It uses NSArray's containsObject: method, which ultimately will call NSObject's isEqual:. Basically, it should work great for arrays of NSStrings, NSNumbers, and maybe NSDates (haven't tried that one yet), but outside of that, YMMV. I imagine if you tried to pass arrays of UITableViewCells or some other really complex object, it would totally sh*t itself, and either crash or return total garbage. Likewise if you were to do something like pass an array of NSDates as the reference array and an array of NSStrings as the source array. Also, if the source array contains items not covered in the reference array, they'll just get discarded. One could address some of these issues by adding a little extra code.
All that said, if you're trying to do something simple, it should work nicely. In your case, you could build up the reference array as you are looping through your setValue:forKey:.
NSMutableArray *referenceArray = [[NSMutableArray alloc] init];
NSMutableDictionary *yourDictionary = [[ NSMutableDictionary alloc] init];
for (//whatever you are looping through here)
{
[yourDictionary setValue://whatever forKey:key];
[referenceArray addObject:key];
}
Then, when you want to loop over your items in the order they came in, you just
for (NSString *key in [self reorderArray:[myDict allKeys] toArray:referenceArray])
Actually you have a reference array in order manner then why you have to add to one more array.So i guess this approach is not good.Please consider my opinion.
Although #GenralMike 's answer works a breeze, it could be optimized by leaving off the unnecessary code as follows:
1) Keep an array to hold reference to the dictionary keys in the order they are added.
NSMutableArray *referenceArray = [[NSMutableArray alloc] init];
NSMutableDictionary *yourDictionary = [[ NSMutableDictionary alloc] init];
for (id object in someArray) {
[yourDictionary setObject:object forKey:someKey];
[referenceArray addObject:someKey]; // add key to reference array
}
2) Now the "referenceArray" holds all of the keys in order, So you can retrieve objects from your dictionary in the same order as they were originally added to the dictionary.
for (NSString *key in referenceArray){
//get object from dictionary in order
id object = [yourDictionary objectForKey:key];
}