How to create an array with particular item from a dictionary? - iphone

I have an application in which i am having the details of the members as a dictionary.i want to add an array with particular object from the dictionary.The response i am having is like this,
{
500 = {
name = baddd;
status = "<null>";
};
511 = {
name = abyj;
status = "Hi all...:-)";
};
512 = {
name = abyk;
status = fdffd;
};
}
I want to create an array with the results of name only.i have tried like this
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSString *name=[NSString stringWithFormat:#"%#",[self.currentChannel.members objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
but the value added is null. can anybody help me ?

Traverse objectEnumerator to get the values (inner dictionaries). Then just add the value of "name" to the resulting array. Example (assuming the dictionary is named d):
NSDictionary* d = ...
NSMutableArray* array = [NSMutableArray arrayWithCapacity:d.count];
for(NSDictionary* member in d.objectEnumerator) {
[array addObject:[member objectForKey:#"name"]];
}

Krumelur was faster than me ;) He is right by saing that you should traverse the dictionary values first. In your implementation you don't reference your counter variable i somewhere, so the NSString name is the same in each iteration.

This may help you..
// here you can get Array of Dictionary First
NSArray *arr = [[NSArray alloc] initWithContentsOfFile:#""]; // get array first from your response
NSDictionary *temp = [[NSDictionary alloc] initWithDictionary:self.currentChannel.members];
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSDictionary *temp = [arr objectAtIndex:i];
NSString *name=[NSString stringWithFormat:#"%#",[temp objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
Thanks.

Related

Array not get data for particular key

Response array like this
NewDataSet = {
Table = (
{
City = {
text = "\nThiruvananthapuram";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
},
{
City = {
text = "\nVellore";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
}
);
text = "\n";
I have write this code..
xmlDictionary = [XMLReader dictionaryForXMLString:xmlResultString error:nil];
NSLog(#"%#",xmlDictionary);
NSLog(#"%#",xmlDictionary);
NSArray * responseArr = xmlDictionary[#"NewDataSet"];
NSLog(#"%#",responseArr);
for(NSDictionary * dic in responseArr)
{
NSLog(#"%#",dic);
//[array1 addObject:[dic valueForKey:#"City"]];
[array1 addObject:[[dic valueForKey:#"City"] valueForKey:#"text"]];
}
but not get the data. in array1. please help me out this thanks in advance.
Problem is i will not get the value in NSDictionary.
Error log is
this class is not key value coding-compliant for the key City.'
I got my Solution problem is i will not get the direct City key. Because City key is under the NewDataSet & Table
so first you go to the NewDataSet and then Table key then finally you get the City key.
Now get array data from Dictionary Like
NSArray * City=[[NSArray alloc]init];
City=[[[xmlDictionary valueForKey:#"NewDataSet"] valueForKey:#"Table"] valueForKey:#"City"];
NSLog(#"%#",City);
pass multiple keys inside key this is the solution.
It seems you haven't allocated array1 anywhere,
Your solution goes here:
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic valueForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
If you have already allocated array1, then please try to log the value for [dic valueForKey:#"City"].
try this code...
for(int i =0;i<[responseArr count];i++)
{
NSString *str = [[responseArr objectAtIndex:i] valueForKey:#"City"];
[array1 addObject:str];
}
let me know it is working or not!!!
Happy Coding!!!
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic objectForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
Try this

Getting Array with values from an array of NSDictionary

I have an array with 4 Dictionaries with key #"preference" like as follows
(
{
preference = Nose;
},
{
preference = "Heart rate";
},
{
preference = Glucose;
},
{
preference = Food;
}
)
Now i want to retrieve an array for these dictionary values like"
(
Nose, Heart rate, Glucose, Food
)
How s'd i get it.. Thanks in advance
A one-liner:
NSArray *resultingArray = [arrayOfDictionaries valueForKeyPath:#"preference"];
Try it:
NSArray *result = [dictionaryObject valueForKeyPath:#"preference"];
It'll solve your Problem
Do something like this:
NSMutableArray *collectedValues = [NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary *dict in array) {
NSString *value = [dict objectForKey:#"preference"];
if (value) {
[collectedValues addObject:value];
}
}
Try with this code:
myArray is your first array
mySecondArray is the array you have in the end
NSMutableArray *mySecondArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [myArray count] ; i++)
{
NSDictionary *tempDict = [myArray objectForIndex:i];
[mySecondArray addObject:[tempDict objectForKey#"preference"]];
}

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

Sort array into dictionary

I have and array of many strings.
I wan't to sort them into a dictionary, so all strings starting the same letter go into one array and then the array becomes the value for a key; the key would be the letter with which all the words in it's value's array begin.
Example
Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."
How can I do that?
Thanks a lot in advance!
NSArray *list = [NSArray arrayWithObjects:#"apple, animal, bat, ball", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in list) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
NSMutableArray *letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
}
NSLog(#"%#", dict);
You can achieve what you want through the following steps:
Create an empty but mutable dictionary.
Get the first character.
If a key for that character does not exist, create it.
Add the word to the value of the key (should be an NSMutableArray).
Repeat step #2 for all keys.
Here is the Objective-C code for these steps. Note that I am assuming that you want the keys to be case insensitive.
// create our dummy dataset
NSArray * wordArray = [NSArray arrayWithObjects:#"Apple",
#"Pickle", #"Monkey", #"Taco",
#"arsenal", #"punch", #"twitch",
#"mushy", nil];
// setup a dictionary
NSMutableDictionary * wordDictionary = [[NSMutableDictionary alloc] init];
for (NSString * word in wordArray) {
// remove uppercaseString if you wish to keys case sensitive.
NSString * letter = [[word substringWithRange:NSMakeRange(0, 1)] uppercaseString];
NSMutableArray * array = [wordDictionary objectForKey:letter];
if (!array) {
// the key doesn't exist, so we will create it.
[wordDictionary setObject:(array = [NSMutableArray array]) forKey:letter];
}
[array addObject:word];
}
NSLog(#"Word dictionary: %#", wordDictionary);
Take a look at this topic, they solves almost the same problem as you — filtering NSArray into a new NSArray in objective-c Let me know if it does not help so I will write for you one more code sample.
Use this to sort the contents of array in alphabetical order, further you design to the requirement
[keywordListArr sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I just wrote this sample. It looks simple and does what you need.
NSArray *names = [NSArray arrayWithObjects:#"Anna", #"Antony", #"Jack", #"John", #"Nikita", #"Mark", #"Matthew", nil];
NSString *alphabet = #"ABCDEFGHIJKLMNOPQRSTUWXYZ";
NSMutableDictionary *sortedNames = [NSMutableDictionary dictionary];
for(int characterIndex = 0; characterIndex < 25; characterIndex++) {
NSString *alphabetCharacter = [alphabet substringWithRange:NSMakeRange(characterIndex, 1)];
NSArray *filteredNames = [names filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF BEGINSWITH[C] %#", alphabetCharacter]];
[sortedNames setObject:filteredNames forKey:alphabetCharacter];
}
//Just for testing purposes let's take a look into our sorted data
for(NSString *key in sortedNames) {
for(NSString *value in [sortedNames valueForKey:key]) {
NSLog(#"%#:%#", key, value);
}
}

Help needed to parse json for iPhone

I want to parse a JSON file in my iphone app. The problem is i can parse simple json files but i am confused how to do parsing on following type of json:
[{"123":
[{ "item_id":"222",
"image_count":"2",
"image_filetype":".jpg",
"image_url":"http:\/\/someurl.jpg",
},
{"item_id":"333",
"image_count":"2",
"image_filetype":".jpg",
"image_url":"http:\/\/someurl.jpg",
}]
}]
Can some on help me how to extract all the img_urls for "123".
Thank you.
NSString *jsonString = …;
// The top-level object is an array
NSArray *array = [jsonString JSONValue];
// The first element in the array is an object containing a name-value
// pair for the key/name "123". The value is itself an array
NSArray *itemsIn123 = [[array objectAtIndex:0] objectForKey:#"123"];
// Use Key-Value Coding to get an array of all values for the key
// image_url
NSArray *imgurls = [itemsIn123 valueForKey:#"image_url"];
Edit based on comments:
Since the top-level array may consist of several objects, each object having a single name-value pair with unknown name, you need to manually iterate over the top-level array:
NSString *jsonString = …;
NSMutableArray *imgurls = [NSMutableArray array];
// The top-level object is an array
NSArray *array = [jsonString JSONValue];
// Each element in the top-level array is an object
for (NSDictionary *outerObject in array) {
// Iterate over all values in the object. Each (single) value is an array
for (NSArray *innerArray in [outerObject allValues]) {
[imgurls addObjectsFromArray:[innerArray valueForKey:#"image_url"]];
}
}
The value for the object "123" will be an NSArray of NSDictionaries. Each of these dictionaries has a key "image_url" for the image url.
The code will depend on which JSON parsing library you use, but the basics should be the same.
First you want to take the key values like 123,112,189 so we will take the keys into an array
say the structure like [ Web { 123 {image url} 112 {image url} 189 {image url} ]
so
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON alloc]init];
NSMutableArray *yourArray1 = [jsonParser objectWithString:responseString]copy]]autorelease;
ufArray = [[yourArray1 valueForKey:#"web"] copy];
for (NSString *s in ufArray) {
[keys addObject:[NSDictionary dictionaryWithObjectsAndKeys:s,#"keys",nil]];
}
NSLOG(#"keys :%#",keys);
// this will contain 112,123,114 etc values
initialize a NSMutableArray
finalArray = [NSMutableArray alloc]init];
for (int i = 0; i < [ufArray count]; i ++) {
yourArray1 = [ufArray valueForKey:[[keys objectAtIndex:i]valueForKey:#"keys"]];
// [keys object at indes:i] - > 123 val / next loop 112 array like that
[finalArray addObject:yourArray1];
}
[jsonParser release];
jsonParser = nil;
Hope this helps!
Well if that array was called jArray
var img_urls = [];
var jL = jArray[0][123].length;
var img_urls = [];
for(var i = 0; i < jL; i++){
img_urls[i] = jArray[0][123][i].image_url;
}
//display in console:
console.log(img_urls);
demo: http://jsfiddle.net/maniator/Vx3hu/4/
I've never used JSON before, never used iPhone before, never used Xcode before...but I would think its something along along the lines of...
//object and image for item ID 222
123: item_id(222).image_url("some_url")
or the second and following items
//hi
123: item_id(333).image_url("some_url")
However something better would be when you can extract the image without the URL by using the item ID and an image ID, so when calling the object 123, you can specify the item id and the image id, which would then output all the information you require. For instance the count, file type and the image could all be displayed.
123: item_id(222).image_id(222)
Is the data file SQL or XML? XML is usually faster! So read up on nodes.
Hope that helps.
DL.