90

Is it possible to get all the keys from a specific NSDictionary as a seperate NSArray?

Jay
  • 913
  • 1
  • 6
  • 4

3 Answers3

191

Just use

NSArray*keys=[dict allKeys];

In general, if you wonder if a specific class has a specific method, look up Apple's own documentation. In this case, see NSDictionary class reference. Go through all the methods. You'll discover many useful methods that way.

Yuji
  • 34,103
  • 3
  • 70
  • 88
  • 3
    To get the first key only is NSString *firstKey = [dict allKeys][0]; – Mazen Kasser Nov 06 '13 at 04:30
  • 2
    @MazenKasser `firstObject` is a safer solution - in case if the dictionary doesn't have any keys the app won't crash: `dict.allKeys.firstObject;` – Islam Oct 20 '15 at 05:12
  • 1
    the order of keys returned by allKeys is undefined... so allKeys.firstObject or allKeys][0] is dangerous either way – Bradley Thomas Feb 24 '17 at 19:39
17

Yes it's possible. Use allKeys method:

NSDictionary *yourDictionary;
NSArray * yourKeys
yourKeys = [yourDictionary allKeys];
gsempe
  • 5,371
  • 2
  • 25
  • 29
3

And if you want to get all keys and values, here's what you do:

for (NSString *key in dictionary) {
    id value = dictionary[key];
    NSLog(@"Value: %@ for key: %@", value, key);
}
awfulcode
  • 597
  • 5
  • 12