3

I currently use a UIStepper in a custom UITableViewCell hooked up to a UITextField to have people select how many items they want to add to their Shopping Cart.

To check if the object is in stock, I've got two numbers: The LocalStock and the TotalStock.

I want to do the following:

If the amount of objects falls into the local stock, I want the textfield the number is displayed in to turn green.

If the amount of objects falls into the supplier stock (so either there is no local stock, or the stepper value is higher than the local stock, so we need to get it from the supplier stock) turn the UITextField blue.

If neither the supplier stock nor local stock are sufficient, I want the textfield to turn yellow.

I got the following code:

- (IBAction)stepperValueChanged:(id)sender

NSLog(@"localstock: %@",localstock);
NSLog(@"TotalStock: %@",totalstock);

NSDecimalNumber *value = [NSDecimalNumber decimalNumberWithString: self.textField.text];

if (value <= localstock) 
{
self.aantalTextField.backgroundColor = [UIColor greenColor]; 

NSLog(@"Value %@ <= Localstock %@ >GREEN< Totalstock: %@",value,localstock, totalstock);
}

else if (value <= totalstock) 
{
self.aantalTextField.backgroundColor = [UIColor blueColor]; 

NSLog(@"Value %@ <= totalstock %@ >BLUE< Localstock: %@",value,totalstock,localstock);
}

else
{
self.aantalTextField.backgroundColor = [UIColor yellowColor]; 
NSLog(@"Value: %@ LocalStock: %@ TotalStock %@ >YELLOW<",value,localstock,totalstock);}}

And it's not making much sense when I run it... Sometimes it catches the GREEN-statement, other times the BLUE, and sometimes the same value returns YELLOW.

Anyone care to take a look at this and show me where the (logical) error is?

Thanks in advance!

blaa
  • 438
  • 5
  • 19

2 Answers2

1

You are comparing objects, not their values. As long they are both of type NSDecimalNumber...you need to compare similar to this.

[value integerValue ] <= [localstock integerValue]
Peter Pajchl
  • 2,699
  • 21
  • 24
  • Thanks! I thought NSDecimalNumber would do logic comparison. Still new to all this stuff, you really helped me out! – blaa Jan 08 '13 at 13:11
1

As far as I understood from your code, localstock, totalstock and value are objects, not integers and you are comparing objects pointers, not values. Instead, you should use the

- (NSComparisonResult)compare:(NSNumber *)decimalNumber

declared in NSDecimalNumber class.

Or convert all to integers using for example

[value intValue]
Michele Percich
  • 1,872
  • 2
  • 14
  • 20
  • Thanks for helping me out too! Too bad I can't mark 2 answers. I'll upvote you instead hehe. – blaa Jan 08 '13 at 13:11
  • @MichelePercich Your answer is obviously correct but I think that is confusing to say that you *can't compare objects using <, <=* - you can (cause for this question), just need to know that in that case you are comparing the object's pointers instead of their values. – Peter Pajchl Jan 08 '13 at 13:18