简体   繁体   中英

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 ?

My NSDictionary look like this :

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 :

"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.

You can use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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