Convert Dictionaries into one array - iphone

This code:
for (NSDictionary *object in JSONArray) {
NSMutableArray *birdtemp = [[NSMutableArray alloc] initWithObjects:object[#"case_name"], nil];
[allparts addObject:birdtemp];
}
outputs this log:
log: (
(
"NZXT Phantom 410"
),
(
"Thermaltake MK+"
)
)
I want to know what code I could use to make that log into one array like:
log: (
"NZXT Phantom 410",
"Thermaltake MK+"
)
Json Array is:
log: (
{
"case_color" = White;
"case_description" = "";
"case_image" = "http://sitecom/get/parts/part_images/nzxtphantom410.jpeg";
"case_name" = "NZXT Phantom 410";
"case_price" = "99.99";
"case_type" = ATX;
id = 1;
},
{
"case_color" = Black;
"case_description" = "";
"case_image" = "http://site.com/get/parts/part_images/thernaltake-mkplus.jpeg";
"case_name" = "Thermaltake MK+";
"case_price" = "84.99";
"case_type" = ATX;
id = 2;
}
)

NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSDictionary *dict in JSONArray) {
[array addObject:[dict objectForKey:#"case_name"]];
}
NSLog(#"Your Array: %#",array);
I think it will be helpful to you.

A simple way to obtain the result you are looking for is to use key-value coding (KVC):
NSArray *allparts = [JSONArray valueForKey:#"case_name"];
Key-value coding used on arrays in this way may seem a bit counter-intuitive at first, but it is very powerful.

Troubleshooted and got this:
allparts = [[NSMutableArray alloc] init];
NSString *birdtemp;
for (NSDictionary *object in JSONArray) {
birdtemp = object[#"case_name"];
[allparts addObject:birdtemp];
}

NSMutableArray *birdtemp = [NSMutableArray ....];
for (NSDictionary *object in JSONArray) {
[birdtemp addObject:object[#"case_name"]];
}
[allparts addObject:birdtemp];

Related

Ios NSDictionary array - grouping values and keys

I have the following result of NSDictionary of Array
Bath = {
Keynsham = (
"nsham companies"
);
};
Bath = {
"Midsomer Norton" = (
"Keynsham companies"
);
};
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
};
Birmingham = {
"Acock's Green" = (
"Acock's Green taxi companies"
);
};
Birmingham = {
"Alcester Lane's End" = (
"Alcester Lane's End taxi companies"
);
};
How can i combine the values and keys so that I end up with only one category as shown below;
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
"Midsomer Norton" = (
"Keynsham companies"
);
Keynsham = (
"nsham companies"
);
};
I am not sure if this is the best way to explain it
the code is as follows
//all Nssarrays allocated/ initialised
NSURL *url=[NSURL URLWithString:#"http://y.php"];
NSData *data= [NSData dataWithContentsOfURL:url];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//instantiate arrays to hold data
NSMutableDictionary *dictArray=[[NSMutableDictionary alloc]init];
NSArray *cityName=[[NSArray alloc]init];
NSArray *townName=[[NSArray alloc]init];
NSArray *taxis=[[NSArray alloc]init];
NSArray *ids=[[NSArray alloc]init];
for (int i=0; i<json.count; i++)
{
//cityName=[[NSMutableArray alloc] initWithCapacity:json.count];
ids = [[json objectAtIndex:i] objectForKey:#"id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName=[[json objectAtIndex:i] objectForKey:#"townName"];
taxis=[[json objectAtIndex:i] objectForKey:#"taxis"];
NSMutableArray *taxisArray=[[NSMutableArray alloc] initWithObjects:taxis,nil];
NSMutableDictionary *towensdict=[[ NSMutableDictionary alloc] initWithObjectsAndKeys:taxisArray,townName, nil];
NSMutableDictionary *cities1=[[NSMutableDictionary alloc] initWithObjectsAndKeys:towensdict,cityName, nil];
NSLOG (#"%#", cities1) here, gives me the print out above
[dictArray addEntriesFromDictionary:cities1 ];
Then I tried Jdodgers solution as follows;
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
NSLog(#"%#", currentDictionary);
}
}
//this gives error "unrecognized selector sent to instance", here is the print out
combinedDictionary NSMutableDictionary * 0x000000010012e580
currentDictionary NSDictionary *const 0x0000000100116460
dictArray NSMutableDictionary * 0x000000010012e220
[0] key/value pair
key id 0x0000000100116460
[0] id
value id 0x000000010012e440
[0] id
keys NSArray * 0x0000000000000000
You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys.
For example, if your array was called dictArray, you could do:
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
}
}
This code first creates a dictionary combinedDictionary that will be your final dictionary. It loops through all of the dictionaries in your array and for each one does the following:
First, it gets an array of all keys in the dictionary. For the dictionaries you provided this array will look like #[#"Bath"] for the first 3 and #[#"Birmingam"] for the other two.
The code then loops through these keys and gets the already existing dictionary from the combined dictionary from this key. If the dictionary doesn't exist, one is created.
Then, it adds all of the values from the dictionary from the array and sets the new dictionary to be the one in combinedDictionary.

Fetch NSarray from the NSDictionary of NSArray using objectForKey

I have a NSArray which contain n number of NSDictionary sampleArray =
(
{
0 = 0;
1 = 0;
},
{
0 = 86400;
1 = 2;
},
{
0 = 172800;
1 = 4;
},
{
0 = 259200;
1 = 5;
}
)
Now I need to fetch the NSArray for objectForKey 0 [sampleArray objectForKey:[NSNumber numberWithInt:0]], my result NSArray should be like
(0,86400,172800,259200) but I am unable to fetch the result and the app crashes.
Normally for NSDictionary, if key value is set using NSString valueForKey the above operation is performed successfully but if key value is set using an object like NSNumber objectForKey I am unable to perform the operation.
Please help me to get a solution, any suggestion would be appreciated!!
A very straight forward way if your keys are NSNumber objects:
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSDictionary *d in a) {
if (d[#0]) {
[result addObject:d[#0]];
}
}
THIS doesnt work - im sorry: I didnt see you didnt have Strings as keys + I didnt know KVC only works with strings
I leave it though
what you are looking for is
NSArray *zeros = [mainArray valueForKey:#"0"];
it gets "0" from each dict in array
What you have do is
NSMutableArray *arrResult = [[NSMutableArray alloc]init];
for(int i=0;i<[sampleArray count];i++)
{
NSString *strValue = [[sampleArray objectAtIndex:i] valueforkey:#"0"];
[ arrResult addobject:strValue];
}
let me know it is working or not!!!!
Happy coding!!!!!
here you can try NSArray *tempArray
for (NSDictionary *list in tempArray)
{
[firstArray addObject:[list objectForKey:#"0"];
[secondArray addObject:[list objectForKey:#"1"];
}

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"]];
}

Removing Object in NSMutable Array using NSMutable Dictionary

i want to remove object in Mutable array using mutable dictionary, How?
My code :
Employees *Emp7 = [[Employees alloc] init];
Emp7.Number = 7;
Emp7.Name = #"Safa'";
[EmployeesArray addObject:Emp1];
[Dictionary setValue:Emp1 forKey:Emp1.Name];
in the Deleting button (IBAction)
Employees *objEmp2 = [Dic1 objectForKey:objEmp1.Name ];
[Dic1 removeObjectForKey:#"Safa'"];
Please be a little more clear with your question, is this what you are looking for ?
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:values forKeys:keys];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
[array removeObject:[dict objectForKey:someKey]];
where 'values' and 'keys' are both arrays and 'somekey' is an object in the 'keys' array.
Please let me know if this helps.
TESTED CODE : 100 % WORKS
NSMutableArray *EmployeesArray = [[NSMutableArray alloc]init];
NSMutableArray *EmployeesArrayToDelete = [[NSMutableArray alloc]init];
Employees *Emp7 = [[Employees alloc] init];
Emp7.number = #"7"; Emp7.Name = #"Safa'";
[EmployeesArray addObject:Emp7];
Employees *Emp3 = [[Employees alloc] init];
Emp3.number = #"7"; Emp3.Name = #"AppleVijay#facebook.com";
[EmployeesArray addObject:Emp3];
Employees *EmployeToDelete = [[Employees alloc] init];
EmployeToDelete.number = #"7";
EmployeToDelete.Name = #"Safa'";
NSLog(#"before delete : %#",EmployeesArray);
for (Employees *eachEmployee in EmployeesArray) {
if ([eachEmployee.Name isEqual:EmployeToDelete.Name] && [eachEmployee.number isEqual: EmployeToDelete.number]) {
[EmployeesArrayToDelete addObject:eachEmployee];
}
}
if ([EmployeesArrayToDelete count]>0) {
[EmployeesArray removeObjectsInArray:EmployeesArrayToDelete];
}
NSLog(#" After delete Employeesarray : %#",EmployeesArray);

Objective-C: NSDictionary and looping through inner NSDictionaries

I get the following NSDictionary when I parse a JSON response from my server:
(
{
fromUname = Ben;
id = ci2n9awef7tm7e142sx;
message = hi;
read = 1;
subject = hi;
time = 1316513972;
toUname = Jill;
},
{
fromUname = Eamorr;
id = asdf98s14u7tm7e142sx;
message = asdf;
read = 0;
subject = asdf;
time = 1316513322;
toUname = Jack;
}
)
I'm really struggling to extract the two subjects.
Here's what I've coded sofar (incomplete...):
...
SBJsonParser *parser=[[SBJsonParser alloc]init];
NSDictionary *obj=[parser objectWithString:[request responseString] error:nil];
NSLog(#"%#",obj);
NSLog(#"%d",[obj count]);
for(int i=0;i<[obj count];i++){
NSDictionary *message=[obj objectForKey:];
NSLog(#"%#",[message objectForKey:#"subject"]); //I'm stuck...
}
...
Can anyone give me some efficient way of extracting the subjects?
Many thanks in advance,
Its actually an NSArray of NSDictionaries. So to get the information, loop through the array and get the dictionary:
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *obj = [parser objectWithString:[request responseString] error:nil];
NSLog(#"%# : %d",obj, [obj count]);
for (NSDictionary *dict in obj) {
NSLog(#"%#", [dict objectForKey:#"subject"]);
}