数组循环问题

时间:2015-06-18 20:16:54

标签: objective-c arrays loops parse-platform cycle

我是iOS新手。我正在制作一个应用程序,我从Parse后端获取数据都工作正常。我的订单和交付食品的申请。我有一个购物车,我添加项目。如果产品已经在购物车中但是又添加了它,它应该增加数量而不是在购物篮中创建另一个产品。我尝试在循环的帮助下实现它,但它不能正常工作。但是添加产品而不是增加产量。我真的希望得到你的帮助。

+ (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 个答案:

答案 0 :(得分:0)

我会使用NSMutableDictionary来存储购物车商品,关键是objectId,价值是Item本身

+ (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"]
    }

答案 1 :(得分:0)

如果您必须使用cart.items作为NSMutalbeArray,则这是另一个答案

+ (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"];
    }
}