简体   繁体   English

从NSDictionary填充NSArray

[英]fill NSArray from NSDictionary

I'm new to Objective-C, and I would like to know how I can fill my NSArray from a NSDictionary ? 我是Objective-C的新手,我想知道如何从NSDictionary中填充NSArray?

My NSDictionary look like this : 我的NSDictionary看起来像这样:

user =     {
    items =         (
                    {
            nom = nom1;
            prenom = prenom1;
        },
                    {
            nom = nom2;
            prenom = prenom2;
        },
                    {
            nom = nom3;
            prenom = prenom3;
        }
    );
};

It is based on a Json, and I want my array to be like : 它基于Json,我希望数组像这样:

"prenom1.nom1", "prenom2.nom2", "prenom3.nom3"

I've tried something like this 我已经尝试过这样的事情

array = [self.users objectForKey:@"user"]

but the result is the same as in my dictionary. 但结果与我的字典相同。

NSDictionary *users = // your dictionary

NSArray *items = users[@"items"];

NSMutableArray *names = [NSMutableArray array];

for (NSDictionary *item in items) {
    NSString *name = [NSString stringWithFormat:@"%@.%@", item[@"prenom"], item[@"nom"]];

    [names addObject:name];
}

Using the dictionary you supplied this will add all the names in the format you wanted to the names array. 使用您提供的字典,这会将所有想要的格式的名称添加到names数组。

You can use enumerateObjectsUsingBlock - 您可以使用enumerateObjectsUsingBlock

NSArray *itemsArray=[user objectForKey:@"items"];

NSMutableArray *outputArray=[[NSMutableArray alloc]init];

[itemsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [outputArray addObject:[NSString stringWithFormat:@"%@.%@",[obj objectForKey:@"prenom"],[obj objectForKey:@"nom"]]];
}];

outputArray will contain your names in the required format outputArray将包含所需格式的名称

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

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