Problems with the loop of the array

62 views Asked by At

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];

}

2

There are 2 answers

1
Mahmoud Adam On BEST ANSWER

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"];
    }
}
6
Mahmoud Adam On

i would use a NSMutableDictionary to store cart items, the key is the objectId and the value is the Item itself

+ (void)addItem:(PFObject *)item {
    Cart *cart = [Cart sharedInstance];
    NSMutableDictionary * cartItems = cart.items
    NSString *objectId = [item valueForKey:@"objectId"];
    if ([cartItems objectForKey:objectId] == nil){
         [cartItems setObject:item forKey:objectId]
    } else {
        PFObject *oldItem = [cartItems objectForKey:objectId];
        int sumQty = [[oldItem valueForKey:@"qty"] intValue] + [[item valueForKey:@"qty"] intValue];
        [cartItems setObject:[NSNumber numberWithInt:sumQty] forKey:@"qty"]
    }