显示NSDictionary中的每个项目

时间:2011-04-08 11:05:25

标签: objective-c iphone xcode nsdictionary

我正在尝试在NSDictionary中显示每个项目。我尝试过使用for循环但是没有用。

6 个答案:

答案 0 :(得分:58)

试试此代码

for(NSString *key in [dict allKeys]) {
  NSLog(@"%@",[dict objectForKey:key]);
}

答案 1 :(得分:25)

怎么样?
NSLog(@"Dictionary: %@", [myDictionary description]);

似乎为我工作......

答案 2 :(得分:0)

如果你想将它保存在NSString上,你可以使用

NSMutableString *stringUserInfo = [[NSMutableString alloc] init];
for (NSString *aKey in dictionary.allKeys)
    [stringUserInfo appendFormat:@"%@ : %@\n",aKey,[dictionary valueForKey:aKey]];

答案 3 :(得分: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;
}*

答案 4 :(得分:-1)

这对我有用,对调试非常有用。

NSDictionary * jsonDictionary = [theJSON JSONValue];

NSLog(@"dictionary data %@",jsonDictionary);

答案 5 :(得分:-2)

我认为您可以使用

打印NSDictionary

NSDictionary * dic;

NSLog(@“nsdic =%@”,dic);

希望得到它的帮助。