程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-如何訪問NSDictionary的內容

ios-如何訪問NSDictionary的內容

編輯:編程綜合問答
如何訪問NSDictionary的內容

在訪問字典內容的時候失敗:

NSLog(@"self.userCommentsArray %@",self.userCommentsArray);返回null。

請幫忙:

NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSDictionary *userCommentsDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    NSLog(@"userCommentsDictionary %@",userCommentsDictionary); // this works
    self.userCommentsArray = [[userCommentsDictionary objectForKey:@"from"] objectForKey:@"name"];
    NSLog(@"self.userCommentsArray %@",self.userCommentsArray); 

這是dicitionary的NSlog輸出:

userCommentsDictionary {
        data =     (
                    {
                created = "2013-07-16T18:42:56+02:00";
                from =             {
                    id = 27;
                    name = "user-4";
                };
                id = 2553;
                message = "liquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
            },
                    {
                created = "2013-07-16T18:42:56+02:00";
                from =             {
                    id = 28;
                    name = "user-5";
                };
                id = 2554;
                message = "x ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
            },
                    {
                created = "2013-07-19T16:18:56+02:00";
                from =             {
                    id = 24;
                    name = "user-1";
                };
                id = 5125;
                message = test comment;
            },
                    {
                created = "2013-07-19T17:00:21+02:00";
                from =             {
                    id = 24;
                    name = "user-1";
                };
                id = 5126;
                message = "test comment ";
       }
        );
        meta =     {
            totalCount = 18;
        };
    }

最佳回答:


userCommentsDictionary 中可以根據data得到一組數據。你要找的內容就在這一組數據中

NSArray *data=userCommentsDictionary[@"data"];

這時返回的是一個數組,你可以根據下標索引取任意一行中的數據,也可以循環遍歷所有的數據。下面的代碼取的是第一行的數據

 id entity=[data objectAtIndex:0];

再取對象中的from下的name

NSString *name=entity[@"from"][@"name"];
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved