开发者

Increment count of duplicate NSDictionary objects in an NSArray?

I am writing a shopping cart application where I have Item Information sent back from server as a NSDictionary object with item number,description,price as values for their keys. I add all these Dictionary objects to mutable array and display in a table view. To manually increment quantity of each item I have added Quantity key to Item Dictionary object.

NSMutableDictionary* itemDictionary = [[NSMutableDictionary alloc] initWithDictionary:inventory.itemDict];
[itemDictionary setObject:[NSString stringWithFormat:@开发者_如何学编程"1"] forKey:@"Quantity"];
[itemsArray addObject:itemDictionary];
[itemDictionary release];
[self.tableView reloadData];

How to increment value for key Quantity if there is a duplicate entry of the same item ? If I add same item to array I would end up with a duplicate, How to find duplicate item i.e., item that has same price, description and item number while ignoring value of Quantity key of the dictionary when searching for duplicates


I would create a new dict containing two items: the inventory dict and the quantity. I'd add an item to itemsArray like this (untested, so beware of typos):

BOOL found = NO;
for (NSDictionary *dict in itemsArray)
{
    if ([[dict objectForKey: @"inventorydict"] isEqual: inventory.itemDict])
    {
        [dict setObject: [NSNumber numberWithInt: 
                          [[dict objectForKey: @"quantity"] intValue] + 1] 
                 forKey: @"quantity"];
        found = YES;
        break;
    }
}

if (!found)
{
    [itemsArray addObject: 
        [NSMutableDictionary dictionaryWithObjectsAndKeys:
            inventory.itemDict, @"inventorydict", 
            [NSNumber numberWithInt: 1], @"quantity",
            nil]];
}

So itemsArray contains NSDictionaries with two keys: "inventorydict" and "quantity". "inventorydict" is the dict passed to you containing the item the user bought, and "quantity" is an NSNumber. When you receive a new product item in the basket, you first check if the item is already in the array. If so, you add one to the "quantity" number, otherwise you create a new dictionary with the inventory item and a quantity of 1.


Store your dictionaries in an NSCountedSet. You can then get the quantity via -countForObject:. Use an array only for presentation purposes, so you can sort the values in a sane way. Rebuild this array whenever the set changes, something like so:

- (void)itemsDidChange
{
    NSCountedSet *itemSet = [self itemSet];
    NSMutableArray *sortedItems = [[NSMutableArray alloc] init];
    for (NSDictionary *item in itemSet) {
        NSUInteger count = [itemSet countForObject:item];
        NSNumber *countNum = [[NSNumber alloc] initWithUnsignedInteger:count];
        NSMutableDictionary *arrayItem = [item mutableCopy];
        [arrayItem setObject:countNum forKey:KEY_QUANTITY];
        [countNum release];
        [sortedItems addObject:arrayItem];
        [arrayItem release];
    }
    [sortedItems sortUsingComparator:/* your comparator here */];
    [self setRowItems:sortedItems];
    [[self tableView] reloadData];
}

Even simpler, use the object directly in your array without changing it at all. When you present the quantity to the user in the UI, just query the itemSet for the count, and use that. The array is then used solely to impose an order on the set's items.


FYI for setObject: you do not need to use stringWithFormat: if you do not have an object to add to it, you can simply use setObject:@"1".

If you want to increment the Quantity, you should be using setObject:[NSNumber numberWithInt:1] instead.


based on Rudy's post made it working this way:

-(void)addToCart:(id)sender 
    {

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    BOOL found = NO;

    NSString *itemName = // get your item name here

    [theDict setObject:itemName forKey:@"name"];

    if ([appDelegate.theCartArray isEqual:nil]) 
    {    
        [appDelegate.theCartArray addObject:theDict];
    }

    else //implementing Rudy's idea
    {

    for (theDict in appDelegate.theCartArray) 
    {
        if ([[theDict objectForKey:@"name"] isEqual:itemName]) 
        {
            [theDict setObject: [NSNumber numberWithInt:
                                [[theDict objectForKey: @"quantity"] intValue] + 1] 
                                forKey: @"quantity"];

            found = YES;

            break;
        }
    }

        if (!found) 
        {
            [appDelegate.theCartArray addObject: 
                             [NSMutableDictionary dictionaryWithObjectsAndKeys: 
                                                  itemName, @"name", 
                                                  [NSNumber numberWithInt: 1], @"quantity",
                                                                                     nil]];
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜