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 回答