これを行う方法は次のとおりです(私が考えることができる最短のもの):
// 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];
}
}
これにより、次のようなdictが得られます。
{
"White Shirts" = 11;
"blue shorts" = 4;
}
したがって、キーを反復処理して、次のような文字列の配列を生成できます。
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in [orderDict allKeys])
{
[results addObject:[NSString stringWithFormat:@"%@ %@", [orderDict valueForKey:key], key]];
}
これにより、最終的に次のことが得られます。
(
"11 White Shirts",
"4 blue shorts"
)
PS。ARC を使用しない場合は、リリースすることを忘れないでください。