【问题标题】:Display each item in an NSDictionary显示 NSDictionary 中的每个项目
【发布时间】:2011-04-08 11:05:25
【问题描述】:

我正在尝试在 NSDictionary 中显示每个项目。我曾尝试使用 for 循环,但没有奏效。

【问题讨论】:

标签: objective-c iphone xcode nsdictionary


【解决方案1】:

试试这个代码

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

【讨论】:

  • 最好在 NSLog 中添加密钥。你可以这样做 - ` NSLog(@"%@ : %@",key, [dict objectForKey:key]); `
  • 自编写此答案以来,新语法已可用。如果您愿意,现在可以使用NSLog(@"%@", dict[key]);..
【解决方案2】:

怎么样

NSLog(@"Dictionary: %@", [myDictionary description]);

似乎对我有用...

【讨论】:

    【解决方案3】:

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

    NSDictionary *jsonDictionary = [JSON JSONValue];

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:
        *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;
        }*
        

        【讨论】:

          【解决方案6】:

          我认为您可以使用打印 NSDictionary

          NSDictionary *dic;

          NSLog(@"nsdic = %@", dic);

          希望有帮助。

          【讨论】:

            猜你喜欢
            • 2011-08-02
            • 2019-08-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-05-12
            相关资源
            最近更新 更多