確定這裏是一個辦法做到這一點(最短的一個我能想到的):
// 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];
}
}
這會給你這樣一個字典:
{
"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,不要忘記發佈!
哇,我深深地謙虛.....這工作很好,我學到了很多......我正準備着手自己編寫一些非常難看的代碼....不知道沒有SO社區我會做什麼....我想寫難看的代碼。非常感謝。 – AhabLives 2012-08-10 21:55:39