Extracting a key/value pair from an NSDictionary - iphone

Is there a convenient way to obtain both a key/value pair from an NSDictionary?
Say I have a NSDictionary, partyGuest,
{
name = "jim";
age = 28;
occupation = "astronaut";
favouriteMeal =
{
starter = "fish head soup";
mainCourse = "roast armadillo";
dessert = "sugar plum fairy cakes";
}
}
I'd like to get obtain a key/value pair within that, like so,
NSDictionary *guestFoodChoice = [partyGuest itemForKey:#"favouriteMeal"];
...and have that obtain both the key and the value,
guestFoodChoice =
{
favouriteMeal =
{
starter = "fish head soup";
mainCourse = "roast armadillo";
dessert = "sugar plum fairy cakes";
}
}
It seems there should be, but as I can't see an obvious method, maybe I'm missing something?

It sounds like you basically want to get a dictionary with some subset (maybe just one) of key-value pairs in another dictionary. If that's right, the Key-Value Coding method dictionaryWithValuesForKeys: is what you want.
NSDictionary *guestFoodChoice = [partyGuest dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"favouriteMeal"]];

See enumerateKeysAndObjectsUsingBlock:.

NSDictionary *guestFoodChoice = [NSDictionary dictionaryWithObjectsAndKeys:[partyGuest itemForKey:#"favouriteMeal"],#"favouriteMeal",nil];

Related

get Values from NSMutableDictionary in swift?

I have a stored NSMutableDictionary in NSUSerDefaluts and i have retrieve that successfully.
if var tempFeed: NSDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey("selectedFeeds") {
println("selected Feed: \(tempFeed)")
savedDictionary = tempFeed.mutableCopy() as NSMutableDictionary
The Question is How can i convert that MutableDictionary into an array/MuatableArray and iterate it so i can get the values of it.Here is the Dictionary. i want to get the values for all URL in that.
{
4 = {
URL = "myurl1";
};
5 = {
URL = "myurl3";
};
6 = {
URL = "myurl3";
};
}
I have tried number of options with failure.
Thank you.
If you want to add all the urls into an array, iterate over it and add append all values to some array.
for (_,urlDict) in savedDictionary {
for(_,url) in urlDict {
urlArr.append(url) // create empty urlArr before
}
}
urlArr now contains all the urls (not ordered)
You can use .values.array on your dictionary to get the values unordered.
as an array
Then, you can just add your NSArray to your NSMutableArray.
var mutableArray:NSMutableArray = NSMutableArray(array: savedDictionary .values.array)
If all you want to do is iterate over it, you don’t have to convert it to an array. You can do that directly:
for (key,value) in savedDictionary {
println("\(key) = \(value)")
}
(if you’re not interested in the key at all, you can replace that variable name with _ to ignore it).
Alternatively, instead of making tempFeed of type NSDictionary, just leave it as the type dictionaryForKey returns, which is a Swift dictionary. This has a .values property, which is a lazy sequence of all the values in the dictionary. You can convert that to an array (so tempFeed.values.array) or perform operations on it directly (use it in for…in, map it such as tempFeeds.values.map { NSURL(string: toString($0)) } etc.)

How to access a certain value in an NSArray?

I have an array called someArray. I would like to access the name value of the NSArray. I'm trying to access it using the following, but with out any luck. How do I do it properly?
cell.textLabel.text = [[someArray objectAtIndex:indexPath.row] objectForKey:#"name"];
some array {
haserror = 0;
headers = {
code = 0;
haserror = 0;
nodeid = "fe1.aaaaaa.2.undefined";
time = 16;
};
results = (
{
coords = (
"44.916667",
"8.616667"
);
id = 2;
key = alessandria;
name = Alessandria;
state = Piemonte;
zip = 1512;
},
{
coords = (
"43.616944",
"13.516667"
);
id = 3;
key = ancona;
name = Ancona;
state = Marche;
zip = 601;
},
}
As far as i see from you data model, the key name is a node under the key results. You can use this data model as a dictionary map, the code snippet below must give you what you need..
NSDictionary *myObject = [[someArray objectAtIndex:indexPath.row] objectForKey:#"results"];
cell.textLabel.text = [myObject objectForKey:"name"];
IMPORTANT NOTE: If you have some lopps or some other mechanisms for receiving data, there may be more efficent ways for your sıolution, so please give some more additional info about what you are exactly tryin to do
As others have noted, someArray is a dictionary while results is a key pointing to an array inside of your dictionary. If you want an array of all of the name fields in your results array, you could use valueForKeyPath: on the someArray variable, like this:
NSArray *names = [someArray valueForKeyPath:#"results.name"];
The names variable should now contain "Alessandria", and "Ancona" from the data set your show in your example code.

Accessing info from NSDictionary based on print out

I'm using NSLog(#"%#", [filter attributes]); to print out the following from a dictionary:
CIAttributeFilterDisplayName = "Color Controls";
CIAttributeFilterName = CIColorControls;
inputBrightness = {
CIAttributeClass = NSNumber;
CIAttributeDefault = 0;
CIAttributeIdentity = 0;
CIAttributeSliderMax = 1;
CIAttributeSliderMin = "-1";
CIAttributeType = CIAttributeTypeScalar;
};
I'm a little confused about NSDictionarys and how the information is organized. If I needed to access the attributes for inputBrightness, what would be the syntax to retrieve this form the dictionary?
If you want to retrieve inputBrightness from dictionary filter, you can try this:
NSDictionary *inputBrightnessDict = filter[#"inputBrightness"]; //or [filter valueForKey:#"inputBrightness"];
This will return another dictionary with key value pairs CIAttributeClass:NSNumber, CIAttributeDefault:0 etc..
You can confirm that filter[#"inputBrightness"] is a dictionary by looking at the NSLog statement. Key value pairs enclosed in { and } represents a dictionary where as ( and ) represents an array.
Inorder to retrieve any value from inputBrightnessDict you can fetch it as, inputBrightnessDict[#"CIAttributeType"];
[filter objectForKey:inputBrightness];
Hope this helps..
Dictionary work with the concept of object and keys. You can retrieve an object using an key. Key-object come as a pair.

Json Parsing issue iOS : missing "

I got a big issue when trying to parse json data in xcode. I have actually tried with two different parser and it still returns me a wrong json. Could anyone help in that ?
The string to parse (called jsonResp) is equal to :
{
"error":false,
"errorMessage":null,
"debugMessage":null,
"count":1,
"list":"links",
"data":[
{
"date":"Jeudi \u00e0 00:00:00",
"type":"friend",
"picture":"http://graph.facebook.com/22222222/picture? type=square",
"name":"Etouda Gaudo",
"ink_id":"1",
"chat_id":"1",
"count":"1",
"last_message":"CoUcou"
}
]
}
the string to parse is equal to :
NSData *jsonData = [jsonResp dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(#"dictionary %#", dictionary);
and then I got the following result for the NSLog of dictionary :
dictionary {
count = 1;
data = (
{
"chat_id" = 1;
count = 1;
date = "Jeudi \U00e0 00:00:00";
"ink_id" = 1;
"last_message" = CoUcou;
name = "Test name";
picture = "http://graph.facebook.com/22222222/picture?type=square";
type = friend;
}
);
debugMessage = "<null>";
error = 0;
errorMessage = "<null>";
list = links;
}
I can't figure out why the " are missing...
Does anyone have a solution.
Thanks in advance.
NSLog is just a print representation for developers to view, it is the result of the description method being called on a class instance. Quotes are only added where the item might be ambitious without them such as a string with an embedded space. To verify that the JSON was parsed correctly validate it with code.
You are deserializing the JSON into an NSDictionary, which doesn't have to have quotes around it's property names, unlike JSON. Your parser is working correctly, but the NSLog of an NSDictionary won't show up exactly the same as the original JSON would.

Extract the values from NSMutableDictionary

(
{
dateVal = "nov 26, 2010";
price = "1 - 195 kr";
},
{
dateVal = "nov 26, 2010";
price = "425 - 485 kr";
},
{
dateVal = "nov 26, 2010";
price = "415 - 640 kr";
})
How can i extract this NSMutableDictionay?
Help me!
You have plenty of choices (I suggest looking into NSArray class reference)
To get dictionary at specific index (whether dictionary you get is mutable or not depends, I think, on how have you created them and put them in array)
// make sure that index is in array bounds
NSDictionary* dict = [yourArray objectAtIndex:index];
NSLog(#"%#", [dict objectForKey:#"dateVal"]); // log date
NSLog(#"%#", [dict objectForKey:#"price"]); // log price
If you want to iterate through all dictionaries you have then you can use fast enumeration:
for (NSDictionary* dict in yourArray){
...
}
It seems to be an Array which contains Dictionnary.
But Vladimir is right, how did you get this ?
To get an item from a Dictionnary, use this :
[ dictionnary objectForKey:#"keyName" ];
Do you mean converting from this string to NSDictionary? It looks like a JSON String for me, doesn't it?
If it is a JSON String and you want to convert to a NSDictionary, you may want to use TouchJSON, some tutorial here