LoginSignup
11
10

More than 5 years have passed since last update.

NSDictionaryの高速列挙(for ... in...)で順番を保証する方法

Last updated at Posted at 2014-10-15

Objective-Cの高速列挙(for ... in ...)は便利ですが、NSDictionaryに対して適用した場合は列挙される順番が保証されません。
順番通りじゃないと困るときの策をメモ。

// 一旦NSDictionaryのキーを取得
NSArray *keys = [dictionary allKeys];

// sortedArrayUsingComparatorを使ってソート
keys = [keys sortedArrayUsingComparator:^(id o1, id o2) {
    return [o1 compare:o2];
}];

// 順番通りに値を取得
for (id key in keys) {
    [array addObject:[dictionary objectForKey:key]];
}

オリジナルのObjectをソートするときはsortedArrayUsingComparatorの中身を変更すれば実装できると思います。

11
10
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10