NSArray with keys help

Discussion in 'iOS Programming' started by mistergreen2011, Apr 16, 2011.

  1. macrumors member

    Joined:
    Mar 23, 2011
    #1
    Hi,

    These are the values of my array
    Code:
    (
            {
            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.
     
  2. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #2
    What "documentations"?
     
  3. macrumors 6502

    seepel

    Joined:
    Dec 22, 2009
    #3
    At first glance I would try filteredArrayUsingPredicate:
     
  4. macrumors 6502

    dantastic

    Joined:
    Jan 21, 2011
    #4
    Read the values into dictionaries instead. Then you can use the keys directly
     
  5. macrumors Pentium

    KnightWRX

    Joined:
    Jan 28, 2009
    Location:
    Quebec, Canada
    #5
    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 :

    Code:
    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.
     
  6. thread starter macrumors member

    Joined:
    Mar 23, 2011
    #6
    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.

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

Share This Page