简体   繁体   English

使用NSdictionary中的数据初始化NSArray

[英]Initialize NSArray with data from NSdictionary

I receiving data from URL, put it in NSDictionary, and then I need to create NSArray for each tags. 我从URL接收数据,将其放在NSDictionary中,然后我需要为每个标签创建NSArray。 My NSDictionary looks like: 我的NSDictionary看起来像:

(
        {
        id =         {
            text = 1;
        };
        logo =         {
            text = "url 1";
        };
        name =         {
            text = "some name 1";
        };
    },
        {
        id =         {
            text = 2;
        };
        logo =         {
            text = "url 2";
        };
        name =         {
            text = "some name 2";
        };
    },
        {
        id =         {
            text = 3;
        };
        logo =         {
            text = "url 3";
        };
        name =         {
            text = "some name 3";
        };
    }   
)

I want to have array like that: arrLogo = (@"url 1", @"url 2", "url 3"). 我希望有这样的数组:arrLogo =(@“url 1”,@“url 2”,“url 3”)。

I'm doing next: arrName=[[dict objectForKey:@"name"] valueForKey:@"text"]; 我正在做下一个: arrName=[[dict objectForKey:@"name"] valueForKey:@"text"];

But Xcode gives me an error: 但是Xcode给了我一个错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance

Problem in the code that I'm trying to initialize an arrays, it's look like that my dict consist of arrays. 在我试图初始化数组的代码中的问题,看起来我的dict由数组组成。 How do I extract the data correctly? 如何正确提取数据?

For this you have to iterate through object of Array that you have. 为此,您必须遍历您拥有的Array对象。 You can use fast enumeration as 您可以使用快速枚举

    for(object in JsonArray){

    NSString *value = [object valueForKey:@"logo"]valueForKey:@"text"]];

     //Add this value  to your array 
    }
}

Hope this helps. 希望这可以帮助。

The JSONResponse you have get is NSArray not NSDictionary 你得到的JSONResponse是NSArray而不是NSDictionary
You can parse you json response like this ... 你可以像这样解析你的json响应......

NSMutableArray * tmpAry = your json response;
NSMutableArray * urlAry = [[NSMutableArray alloc] init];

for (int i=0; i<tmpAry.count; i++) {
     NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
     [urlAry  addObject:[[tmpDictn objectForKey:@"logo"] valueForKey:@"text"]];
 }
NSLog(@"urlAry : %@",urlAry);

Log will display : 日志将显示:

urlAry : (
            url 1,
            url 2,
            url 3
            )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM