I executed the following code NSLog(@"%@", arrData); and the output in the debugger was expected like so:
"0." = {
"first_name"="John"
};
"1." = {
"first_name"="Florence"
};
"2." = {
"first_name"="Melinda"
};
"3." = {
"first_name"="Zack"
};
I then executed this code:
for (NSDictionary *book in arrData)
{
NSLog(@"%@ %@" , book, [[arrData objectForKey:book] objectForKey:@"first_name"]);
}
And the output was like so:
2. Melinda
0. John
3. Zack
1. Florence
How do I make the for loop print the results in the same order as ? NSLog(@"%@", arrData);
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:So,
%@takes any Objective-C or CFTypeRef object. Since you are using aNSDictionary,%@will print the output of description ordescriptionWithLocale:(id)locale. So what does that do? Again, from Apple’s documentation: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:
I hope this clears things up.