views:

312

answers:

2

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;
    }
+3  A: 

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];
Wevah
+2  A: 

NSDictionaries are unordered, meaning that there are not first or last element. In fact, the order of the keys are never guaranteed to be the same, even in the lifetime of a specific dictionary.

If you want any object, you can get one of the keys:

id key = [[message allKeys] objectAtIndex:0]; // Assumes 'message' is not empty
id object = [message objectForKey:key];
Martin Cote