Ok ici est une façon de le faire (la plus courte que je pouvais penser):
// Assuming that 'orders' is the array in your example
NSMutableDictionary *orderDict = [[NSMutableDictionary alloc] init];
for (NSString *order in orders)
{
// Separate the string into components
NSMutableArray *components = [[order componentsSeparatedByString:@" "] mutableCopy];
// Quantity is always the first component
uint quantity = [[components objectAtIndex:0] intValue];
[components removeObjectAtIndex:0];
// The rest of them (rejoined by a space is the actual product)
NSString *item = [components componentsJoinedByString:@" "];
// If I haven't got the order then add it to the dict
// else get the old value, add the new one and put it back to dict
if (![orderDict valueForKey:item])
[orderDict setValue:[NSNumber numberWithInt:quantity] forKey:item];
else{
uint oldQuantity = [[orderDict valueForKey:item] intValue];
[orderDict setValue:[NSNumber numberWithInt:(oldQuantity+quantity)] forKey:item];
}
}
cela vous donne un dict comme ceci:
{
"White Shirts" = 11;
"blue shorts" = 4;
}
Ainsi, vous pouvez parcourir les clés et produire un tableau de chaînes comme ceci:
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in [orderDict allKeys])
{
[results addObject:[NSString stringWithFormat:@"%@ %@", [orderDict valueForKey:key], key]];
}
Ce qui finalement vous donnera:
(
"11 White Shirts",
"4 blue shorts"
)
PS. N'oubliez pas de libérer si vous n'utilisez pas ARC!
Wow, je suis profondément humiliée ..... cela a fonctionné magnifiquement et j'ai appris une tonne ... J'étais sur le point de me lancer dans un code très moche par moi-même ... Je ne sais pas ce que je ferais sans la communauté SO .... Je suppose que j'écris du code moche. Merci beaucoup. – AhabLives