PDA

View Full Version : NSArray with keys help




mistergreen2011
Apr 16, 2011, 09:43 PM
Hi,

These are the values of my array
(
{
K = "39.0983";
NO3 = "62.0049";
mass = "101.1032";
name = KNO3;
solubility = "360.0";
teaspoon = "5.3";
},
{
K = "39.0983";
PO4 = "94.9714";
mass = "136.086";
name = KH2PO4;
solubility = "22.0";
teaspoon = "5.60";
}
)


How do you query the array saying, find the mass where name = "KNO3"?

This has me stumped. The documentations show you how to make them but not get a specific value.

thanks.



dejo
Apr 16, 2011, 10:01 PM
The documentations show you how to make them but not get a specific value.
What "documentations"?

seepel
Apr 16, 2011, 11:09 PM
At first glance I would try filteredArrayUsingPredicate:

dantastic
Apr 17, 2011, 08:17 AM
Read the values into dictionaries instead. Then you can use the keys directly

KnightWRX
Apr 17, 2011, 09:04 AM
Seems to me there's 2 things in your posts you're trying to mash up into 1 array.

You seem to have 2 different object instances there. What you want is probably more an NSArray composed of either NSDictionary objects or your own class for defining what seems to be Chemicals. Anyway, with NSDictionary :


NSMutableArray * array = [[NSMutableArray alloc] init];
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"39.0983", @"K",
@"62.0049", @"NO3",
...
];

[array addObject: dict];
dict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"39.0983", @"K",
@"94.9714", @"PO4",
...
];
[array addObject: dict];

NSLog(@"K for object 1 is : %s", [[array objectAtIndex: 1] objectForKey: @"K"]);



Don't try to mash complex data structures into 1 object. Decompose into as many objects as needed and assemble them so you can then easily query your stuff without overly complex indexes/keys.

mistergreen2011
Apr 17, 2011, 02:39 PM
Seems to me there's 2 things in your posts you're trying to mash up into 1 array.

You seem to have 2 different object instances there. What you want is probably more an NSArray composed of either NSDictionary objects or your own class for defining what seems to be Chemicals. Anyway, with NSDictionary :

Don't try to mash complex data structures into 1 object. Decompose into as many objects as needed and assemble them so you can then easily query your stuff without overly complex indexes/keys.

Thanks a bunch... Yeah, stuffing it into one object is a problem. I wrote a loop and it seemed to work but I'll try the simpler method.


for(int i=0; i < [shared.elements count]; i++) {
if([[shared.elements objectAtIndex:i] valueForKeyPath:@"ferts.name"] == @"KH2PO4") {
NSLog(@"found it %@", [[shared.elements objectAtIndex:i] valueForKeyPath:@"ferts.mass"]);
}

}