ios 比较两个 NSNumber 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10428526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:14:06  来源:igfitidea点击:

Comparing two NSNumber objects

ioscomparisonnsnumber

提问by USK

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

我用这个代码来比较两个NSNumber的对象,但它从来没有过的,如果条件。

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?

怎么了?

回答by Saad

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

我会避免对象比较

回答by Nitin

Change following code..

更改以下代码..

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

Hope, this will help you..

希望能帮到你..

回答by Deviator

Try comparemethod instead of '=='.

尝试比较方法而不是“==”。

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

Tell me if it helps now!

现在告诉我它是否有帮助!

回答by vishiphone

Use like this I thing this will helpful for you

像这样使用我的东西这对你有帮助

NSNumber *n=[[NSNumber alloc]init];
if([n isEqualToNumber:somenumber])
 {
 }