Reputation: 71
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.
Upvotes: 1
Views: 998
Reputation: 114846
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
Upvotes: 2
Reputation: 77641
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.
Upvotes: 2