iphoneobjective-ccocoacocoa-touchnsdictionary

How can I get the first element in an NSDictionary?


I have an array of NSDictionaries. How can I pull out the first element in the dictionary?

   NSArray *messages = [[results objectForKey:@"messages"] valueForKey:@"message"];         
    for (NSDictionary *message in messages)
    {
        STObject *mySTObject = [[STObject alloc] init];
        mySTObject.stID = [message valueForKey:@"id"];      
        stID = mySTObject.stID;
    }

Solution

  • [Updated to use firstObject, as described in another answer, which has the benefit of returning nil for an empty array.]

    There is no "first" element in an NSDictionary; its members have no guaranteed order. If you just want one object from a dictionary, but don't care which key it's associated with, you can do:

    id val = yourDict.allValues.firstObject;
    

    (There's also lastObject, which has been around since 10.0(!).)

    (Old, pre 10.6 version:)

    id val = nil;
    NSArray *values = [yourDict allValues];
        
    if ([values count] != 0)
        val = [values objectAtIndex:0];