Comparing two NSNumber objects
Asked Answered
A

4

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?

Arrhenius answered 3/5, 2012 at 9:22 Comment(1)
Try with isEqual instant of ==.Profession
E
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

Evangelicalism answered 3/5, 2012 at 9:30 Comment(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])Bucher
M
30

Change following code..

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

Hope, this will help you..

Mockheroic answered 3/5, 2012 at 9:26 Comment(1)
This is the best answer.Hennessy
M
13

Try compare method instead of '=='.

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

Tell me if it helps now!

Middlebrooks answered 3/5, 2012 at 9:25 Comment(1)
it come error: -[NSCFString isEqualToNumber:]: unrecognized selector sent to instance 0x753e5e0'Arrhenius
P
2

Use like this I thing this will helpful for you

NSNumber *n=[[NSNumber alloc]init];
if([n isEqualToNumber:somenumber])
 {
 }
Profession answered 3/5, 2012 at 9:27 Comment(2)
it shown this erro -[NSCFString isEqualToNumber:]: unrecognized selector sent to instance 0x753e5e0'Arrhenius
Because I dont know what is your productObject.pid.for comparing both should be number so check that.Profession

© 2022 - 2024 — McMap. All rights reserved.