28

I used this code to compare two NSNumber objects, but it never passed the if condition.

listItems = [appDelegate.productStatus componentsSeparatedByString:@","];


for (int i=0;i<[appDelegate.productArray count]; i++)
{

    for (int j=0; j<[listItems count]; j++) 
    {
        number=[NSNumber numberWithInt:[[listItems objectAtIndex:j] intValue]];
        NSLog(@"number %@",number);
        productObject=[appDelegate.productArray objectAtIndex:i];           
        NSLog(@"%@,%@",productObject.pid,number);
        if (productObject.pid == number) 
        {
            NSLog(@"BUY it!!!");
            [purchasArray addObject:productObject];
        }

    }
}

What is wrong?

Michal
  • 15,429
  • 10
  • 73
  • 104
USK
  • 499
  • 1
  • 4
  • 9

4 Answers4

50

My sugestion is to compare it as

if([productObject.pid intValue] == [number intValue])
{
 NSLog(@"BUY it!!!");
        [purchasArray addObject:productObject];
}

cheers.

I'd avoid object comparison

Lucas
  • 6,675
  • 3
  • 25
  • 43
Saad
  • 8,857
  • 2
  • 41
  • 51
  • 1
    right, but [number intValue] ain't necessary, because number is built from a int few lines above. so it could be if([productObject.pid intValue] == [[listItems objectAtIndex:j] intValue]) – Kai Huppmann May 03 '12 at 09:37
30

Change following code..

if ([productObject.pid isEqualToNumber number]) 
    {
        NSLog(@"BUY it!!!");
        [purchasArray addObject:productObject];
    }

Hope, this will help you..

Nitin
  • 7,455
  • 2
  • 32
  • 51
13

Try compare method instead of '=='.

if([1stNum compare:secNum] == NSOrderedSame) 
  {
      // do something
  }

Tell me if it helps now!

Deviator
  • 688
  • 3
  • 7
  • it come error: -[NSCFString isEqualToNumber:]: unrecognized selector sent to instance 0x753e5e0' – USK May 03 '12 at 09:32
2

Use like this I thing this will helpful for you

NSNumber *n=[[NSNumber alloc]init];
if([n isEqualToNumber:somenumber])
 {
 }
vishiphone
  • 750
  • 7
  • 14
  • 1
    it shown this erro -[NSCFString isEqualToNumber:]: unrecognized selector sent to instance 0x753e5e0' – USK May 03 '12 at 09:33
  • Because I dont know what is your productObject.pid.for comparing both should be number so check that. – vishiphone May 03 '12 at 09:36