How can I get the first element in an NSDictionary?

Sheehan Alam picture Sheehan Alam · Apr 23, 2010 · Viewed 51.3k times · Source

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

Answer

Wevah picture Wevah · Apr 23, 2010

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 = nil;
NSArray *values = [yourDict allValues];

if ([values count] != 0)
    val = [values objectAtIndex:0];