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];
}
If you had to use
cart.items
asNSMutalbeArray
, here is another answer