5

次のコードを実行したNSLog(@"%@", arrData);ところ、デバッガーでの出力は次のように期待されていました。

    "0." =     {
"first_name"="John"
    };

    "1." =     {
"first_name"="Florence"
    };

    "2." =     {
"first_name"="Melinda"
    };
    "3." =     {
"first_name"="Zack"
    };

次に、次のコードを実行しました。

for (NSDictionary *book in arrData)
{
        NSLog(@"%@ %@" , book, [[arrData objectForKey:book]  objectForKey:@"first_name"]);
}

そして、出力は次のようになりました。

2. Melinda
0. John
3. Zack
1. Florence

forループで結果を同じ順序で出力するにはどうすればよいですか?NSLog(@"%@", arrData);

4

1 に答える 1

8

A few things are going on here.

First let's understand what %@ means in NSLog. Many iOS/Cocoa developers incorrectly believe %@ is associated with NSString, it's not. From Apple's documentation:

Objective-C object, printed as the string returned by descriptionWithLocale:if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.

So, %@ takes any Objective-C or CFTypeRef object. Since you are using a NSDictionary, %@ will print the output of description or descriptionWithLocale:(id)locale. So what does that do? Again, from Apple's documentation:

If each key in the dictionary is an NSString object, the entries are listed in ascending order by key, otherwise the order in which the entries are listed is undefined.

When using the for-in loop, aka Fast-Enumeration, the order of the objects is undefined, so that is why the output of the loop is not in order. If you wanted to print the contents of an NSDictionary in order, you'll have to emulate the behavior of the description method.

From this stackoverflow post:

NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys) {
    [sortedValues addObject: [dict objectForKey: key]];
}

I hope this clears things up.

于 2012-11-15T21:19:21.237 に答える