I am trying to display each item in NSDictionary. I have tried using a for loop but that didn't work.
Asked
Active
Viewed 4.8k times
29
-
2possible duplicate of [Enumerate NSDictionary with keys and objects, PHP style](http://stackoverflow.com/questions/3775507/enumerate-nsdictionary-with-keys-and-objects-php-style) – Apr 08 '11 at 11:09
-
If this doesn't get closed as a duplicate, alanvabraham, could you please explain what for-loop you tried using and how it failed to work? – Gareth McCaughan Apr 08 '11 at 11:10
6 Answers
75
Try this code
for(NSString *key in [dict allKeys]) {
NSLog(@"%@",[dict objectForKey:key]);
}

PgmFreek
- 6,374
- 3
- 36
- 47
-
1Better to add key in NSLog as well. You can do - ` NSLog(@"%@ : %@",key, [dict objectForKey:key]); ` – Aniket Thakur May 12 '18 at 05:43
-
Since this answer was written, new syntax has become available. You can now do `NSLog(@"%@", dict[key]);` if you prefer.. – Alex Meuer Aug 30 '18 at 09:07
34
What about
NSLog(@"Dictionary: %@", [myDictionary description]);
Seems to work for me...

Nick
- 2,803
- 1
- 39
- 59
2
This works for me and is very useful for debugging.
NSDictionary *jsonDictionary = [theJSON JSONValue];
NSLog(@"dictionary data %@",jsonDictionary);

WalesTales
- 41
- 1
0
And if you want to save it on NSString you can use
NSMutableString *stringUserInfo = [[NSMutableString alloc] init];
for (NSString *aKey in dictionary.allKeys)
[stringUserInfo appendFormat:@"%@ : %@\n",aKey,[dictionary valueForKey:aKey]];

TechValens
- 437
- 6
- 20
0
*Try this simple example:
//.h file
@interface DictionaryClass : NSObject
{
NSDictionary *dict;
}
-(void) intialiseDictionary;
-(void) displayDictonary;
-------------------------------------------------------
//.m file
#import "DictionaryClass.h"
@implementation DictionaryClass
-(void) intialiseDictionary
{
dict = @{@"key1":@"object1",@"key2":@"object2",@"key3":@"object3",@"key4":@"object4"};
}
-(void) displayDictonary
{
for(NSString *keys in dict)
{
NSLog(@"\n Dictionary object = %@",[dict objectForKey:keys]);
}
}
@end
-------------------------------------------------------
//main function
#import <Foundation/Foundation.h>
#import "DictionaryClass.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
DictionaryClass *obj = [[DictionaryClass alloc]init];
[obj intialiseDictionary];
[obj displayDictonary];
}
return 0;
}*

Vaibhav Shiledar
- 939
- 8
- 15
-3
i think you can print NSDictionary using
NSDictionary *dic;
NSLog (@"nsdic = %@", dic);
Hope its help.

Pankaj Gadhiya
- 199
- 2
- 8