How can I get the first element in an NSDictionary? - iphone

I have an array of NSDictionaries. How can I pull out the first element in the dictionary?
NSArray *messages = [[results objectForKey:#"messages"] valueForKey:#"message"];
for (NSDictionary *message in messages)
{
STObject *mySTObject = [[STObject alloc] init];
mySTObject.stID = [message valueForKey:#"id"];
stID = mySTObject.stID;
}

There is no "first" element in an NSDictionary; its members have no guaranteed order. If you just want one object from a dictionary, but don't care which key it's associated with, you can do:
id val = nil;
NSArray *values = [yourDict allValues];
if ([values count] != 0)
val = [values objectAtIndex:0];

NSDictionaries are unordered, meaning that there are not first or last element. In fact, the order of the keys are never guaranteed to be the same, even in the lifetime of a specific dictionary.
If you want any object, you can get one of the keys:
id key = [[message allKeys] objectAtIndex:0]; // Assumes 'message' is not empty
id object = [message objectForKey:key];

NSArray has a selector named firstObject that simplifies the code and makes it more readable:
id val = [[yourDict allValues] firstObject];
If yourDict is empty val will be nil, so is not necessary to check the dictionary/array size.

Simplest:
[[dict objectEnumerator] nextObject];

According to Apple, calls to allKeys or allValues incur the cost of creating new arrays:
A new array containing the dictionary’s values, or an empty array if
the dictionary has no entries (read-only)
So, an alternative option that does not incur such cost could look like this:
NSString* key = nil;
for(key in yourDict)
{ // this loop will not execute if the dictionary is empty
break; // exit loop as soon as we enter it (key will be set to some key)
}
id object = yourDict[key]; // get object associated with key. nil if key doesn't exist.
Note: If the dictionary is empty, the key will remain nil, and the object returned will also be nil, we therefore don't need special handling of the case where the dictionary is actually empty.

If someone is still looking for answer for this type of situation then can refer this:
// dict is NSDictionary
// [dict allKeys] will give all the keys in dict present
// [[dict allKeys]objectAtIndex:0] will give from all the keys object at index 0 because [dict allKeys] returns an array.
[[dict allKeys]objectAtIndex:0];

If you have NSDictionary named message,
It's pretty simple:
message[[[message allKeys] objectAtIndex:0]];
But you have to be sure (or better check) that your dictionary has at least one element.
Here is how you can check it:
if ([message allKeys] > 0) NSLog(#"%#", message[[[message allKeys] objectAtIndex:0]]);
But NSDictionary has no guaranteed order, so you probably should use this code only if your dictionary has only one element.
[UPDATE]
It's also good idea to use this if you need to get ANY element of dictionary

Try this:
NSDictionary *firstValue = [responseObject objectAtIndex:0];

Related

Keeping KEYS in correct ORDER in NSDictionary/NSArray from JSON

I have a JSON array returning from a request.
Data is as such (it comes from external source and cannot be changed from server):
[{"clients":
{"name":"Client name here","telephone":"00000","email":"clientemail#hotmail.com","website":"www.clientname.com"}
}]
I receive the JSON array in this order.
I have the below Objective-C:
//jsonString is the json string inside type NSString.
NSMutableDictionary *tempDict = [jsonString JSONValue];
NSMutableDictionary *clients = [tempDict objectForKey:#"clients"];
for(NSString *key in clients) {
id value = [tempDict objectForKey:key];
for(NSString *itemKey in key) {
NSLog(#"ITEM KEY %#: ",itemKey);
}
}
The order it prints keys is:
telephone
email
name
web site
I need it to print how it is received (eg):
name
telephone
email
web site
I have read that Dictionaries are unsorted by definition so am happy to use an Array instead of a dictionary.
But I have seen SEVERAL threads on StackOverflow regarding possible solution (using keysSortedByValueUsingSelector):
Getting NSDictionary keys sorted by their respective values
Can i sort the NSDictionary on basis of key in Objective-C?
sort NSDictionary keys by dictionary value into an NSArray
Can i sort the NSDictionary on basis of key in Objective-C?
I have tried them and am getting nowhere. Not sure if it is just my implementation which is wrong.
I tried (attempt 1):
NSArray *orderedKeys = [clients keySortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare:obj2];
}];
for(NSString *key in orderedKeys) {
id value = [tempDict objectForKey:key];
for(NSString *keyThree in key) {
NSLog(#"API-KEY-ORDER %#: ",keyThree);
}
}
Receive error: [__NSArrayM keySortedByValueUsingComparator:]: unrecognized selector sent to instance.
Also tried (attempt 2):
NSArray *sortedKeys = [[clients allKeys] sortedArrayUsingSelector: #selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys){
[sortedValues addObject: [tempDict objectForKey: key]];
//[sortedValues addObject: [all objectForKey: key]]; //failed
}
But another error on selector even though clients is a NSMutableDictionary.
[__NSArrayM allKeys]: unrecognized selector sent to instance 0x4b6beb0
I am at the point where I think I am going to iterate over the NSMutableDictionary and manually place them into a new NSMutableArray in the correct order.
Any ideas would be very much appreciated?
OR anybodies code snippet attempt at my problem would be equally appreciated.
Not only is NSDictionary in principle unordered, but so are JSON objects. These JSON objects are identical:
[{"clients":
{"name":"Client name here","telephone":"00000","email":"clientemail#hotmail.com","website":"www.clientname.com"}
}]
[{"clients":
{"website":"www.clientname.com","name":"Client name here","telephone":"00000","email":"clientemail#hotmail.com"}
}]
If the server wants to have ordered keys, it needs to send an array. Of course you can just use the keysSortedByValueUsingComparator: method to get the keys in a sorted order.
First, the exception you're seeing is because the selector name is incorrect. You should use keysSortedByValueUsingComparator.
Second, you can't sort the keys, because the order in which you're getting them from the server doesn't seem to be in any particular order. If you MUST have them in that order, then send them from the server with a tag ("index") and then sort by this tag.

Moving through a NSDictionary getting objects that you do not know the 'Key' for? IOS

I have a NSDictionary that I get from a webservice. Each object in this dictionary contains an array. I do not know how many objects there are going to be in the NSDictionary, or what the 'Key' for each object is going to be beforehand. I only know that it will be a Dictionary of arrays.
How can I enumerate through the dictionary reading out the name of the Object and its content into arrays?
All my dealings with Dictionaries so far I could use
[anotherDict objectForKey:#"accounts"]
because I know the 'Keys; to expect beforehand.
Many Thanks,
-Code
NSDictionary has the method: enumerateKeysAndObjectsUsingBlock: since iOS 4.0. It's very straightforward, it receives a block object to operate on entries in the dictionary.
An example:
[anotherDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *arr = obj;
//Do something
}
NSDictionary class has an instance method -allKeys which returns an NSArray with NSStrings for all the keys.
Simplest Way WOuld be to fetch allKeys via the allKeys instance method
NSArray *keys = [myDictionary allKeys];
then iterating over dictionary with for each key.
for (NSString *k in keys)
{
id object = [myDictionary objectForKey:k];
}
You can also get keys in order as if values were sorted using
NSArray *sortedKeys = [myDictionary keysSortedByValueUsingSelector:#selector(compare:)];
you can do this :
NSArray * keys = [dictionnary allKeys];
for (NSString *key in keys) {
NSArray *tmp = [dictionnary objectForKey:key];
}
i am not a pro but i know that you can get all the keys of an dictionary
NSLog(#"%#",[Your_Dictionary allKeys]);
This will give an array of keys in that dictionary.

How to retrieve String from NSDictionary in objective C?

I am trying to retrieve the value for a key in a NSDictionary. The dictionary has been initialised with key value pairs both of type string. The trouble is, I cannot seem to retrieve the value with I call objectForKey or valueForKey.
I am able to iterate over the dictionary and print both keys and values.
Can someone point out where im going wrong? Here is my code...
//Set up dictionary with options
keys = [NSArray arrayWithObjects:#"red", #"blue", nil];
values = [NSArray arrayWithObjects:#"1.7", #"2.8", nil];
conversionOptions = [NSDictionary dictionaryWithObject:values
forKey:keys];
Then this is called on the select row in a picker
NSLog(#"... %#", [keys objectAtIndex:row]); //prints out the key
NSString *theString = [keys objectAtIndex:row]; //save it as a string
NSLog(#"The string is... %#", theString); //print it out to make sure im not going crazy
NSLog(#"the value is : %#",[conversionOptions objectForKey:theString]); // I just get NULL here
//NSLog(#"the value is : %#",[conversionOptions valueForKey:theString]); // This doesn't work either, I just get NULL
You're creating a dictionary with an array as the only key and an array for its value! You want the dictionaryWithObjects:forKeys: (plural) factory, not dictionaryWithObject:forKey: (singular) so that each element of the keys array will be used as a distinct key for the respective element of the values array.
I find the dictionaryWithObjectsAndKeys: factory to be more useful most of the time, e.g.:
conversionOptions = [NSDictionary dictionaryWithObjectsAndKeys:#"1.7", #"red", #"2.8", #"blue", nil];
This is how you retrieve a string from a dictionary object
NSString * string = [dictionary objectForKey:#"stringKey"];
Use objectForKey: not valueForKey:.
Make sure conversionOptions is non-nil when you call objectForKey: (which is the right method).
And, yeah, derp -- I missed that the wrong factory method was used. You could do dictionaryWithObjects:andKeys: or do what pmjordan said said.
You absolutely must use objectForKey:, though. valueForKey: is specific to KVC.

NSMutableArray:How to allow duplicate values

I'm reading a JSON code such as:
[{"question_id":"1",
"trigger_value":"Yes",
"question_text":"What is your first name?",
"question_type":"YN"},
{"question_id":"2",
"trigger_value":"Yes",
"question_text":"What is your second name?",
"question_type":"YN"}
]
But once it's set into NSMutableArray, the duplicate values are deleted. I would like to allow them to check the question_type for each question.
NSString *question_id;
NSString *question_text;
NSString *question_type;
while (dicjson = (NSDictionary*)[enumerator nextObject]) {
question_id = [dicjson objectForKey:#"question_id"];
question_type = [dicjson objectForKey:#"question_type"];
[mutjson setObject:question_id forKey:question_type];
}
Would you give me any idea of allowing duplicate values...?
Thanks in advance.
mutjson looks like a mutable dictionary and not a mutable Array.
So yes, in a dictionary object if you are setting the same key, it will overwrite the previous value.
If you need to store dictionary object, create a mutable array and add each object inside that array as a dintionary object...
NSMutableArray *results = [[NSMutableArray alloc] init];
while (dicjson = (NSDictionary*)[enumerator nextObject]) {
question_id = [dicjson objectForKey:#"question_id"];
question_type = [dicjson objectForKey:#"question_type"];
[result addObject:[NSDictionary dictionaryWithObject:question_id forKey:question_type]];
}
You cannot setObject:forKey: in NSMutableArray. You have to use addObject:. Its also much easier to create the array like this:
NSArray *values = [jsonDict allValues];
You are confusing an array for a dictionary. An array can hold duplicate values. A dictionary cannot hold duplicate keys.
The JSON response is an array of dictionaries. The way you've written your code, specifically [mutjson setObject:question_id forKey:question_type]; seems to suggest that you are simply using a dictionary.
If you would like to check the question type for each question, try instead:
NSString *question_type;
for (NSMutableDictionary *dict in dicjson) {
// I would suggest renaming dicjson to something more descriptive, like results
question_type = [dict objectForKey: #"question_type"];
// Do what you would like now that you know the type
}

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.