Search code examples
objective-carraysloopsparse-platformcycle

Problems with the loop of the array


I am new in iOS. I am making an app in which i am getting data from Parse back-end all are working fine. My application for the order and delivery of food. I have a cart where I add items. If the product is already in the cart but added it again, it should increase the quantity and not create another one in the basket. I tried to implement it with the aid of loop but it is not working as it should. But the product is added instead of increasing their quantity. I really hope for your assistance.

+ (void)addItem:(PFObject *)item {

Cart *cart = [Cart sharedInstance];

for (NSUInteger i = 0; i < [cart.items count]; i++) {
    if ([item valueForKey:@"objectId"] == [cart.items[i] valueForKey:@"objectId"]) {

        NSDecimalNumber *sumQtyNew = [NSDecimalNumber decimalNumberWithMantissa:1 exponent:0 isNegative:NO];
        NSDecimalNumber *sumQty = [NSDecimalNumber decimalNumberWithMantissa:1 exponent:0 isNegative:NO];

        sumQtyNew = [item valueForKey:@"qty"];
        sumQty =  [cart.items[i] valueForKey:@"qty"];
        sumQty = [sumQty decimalNumberByAdding:sumQtyNew];

        [[cart.items[i] valueForKey:@"objectId"] setObject:sumQty forKey:@"qty"];

    }
    else {
        [cart.items addObject:item];
    }
}

NSDecimalNumber *plus = [[NSDecimalNumber alloc]initWithString:[item objectForKey:@"price"]];
cart.totalPrice = [cart.totalPrice decimalNumberByAdding:plus];

}


Solution

  • If you had to use cart.items as NSMutalbeArray, here is another answer

    + (void)addItem:(PFObject *)item {
        Cart *cart = [Cart sharedInstance];
        NSMutableArray * cartItems = cart.items
        NSString *objectId = [item valueForKey:@"objectId"];
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"objectId = %@", objectId];
        PFObject *existingItem = [[cartItems filteredArrayUsingPredicate:predicate] firstObject];
    
        if (existingItem == nil){
            [cartItems addObject:item];
        } else {
            int sumQty = [[existingItem valueForKey:@"qty"] intValue] + [[item valueForKey:@"qty"] intValue];
            [existingItem setObject:[NSNumber numberWithInt:sumQty] forKey:@"qty"];
        }
    }