Comparing NSNumbers in Objective C

前端 未结 4 1021
遇见更好的自我
遇见更好的自我 2020-11-30 05:29

I am a beginner at Objective-C and I am a bit confused at this scenario. I have the following code:

if (number1 < number2) {
    NSLog(@\"THE FOLLOWING NU         


        
相关标签:
4条回答
  • 2020-11-30 05:44

    Swift 3.1

    let number1 = NSNumber(value: 10.2)
    let number2 = NSNumber(value: 20.2)
    let result = number1.compare(number2)
    if  result == .orderedAscending {
    
    } else if result == .orderedDescending {
    
    } else { // .orderedSame
    
    }
    
    0 讨论(0)
  • 2020-11-30 05:57

    For cases where you simply want to test whether two NSNumber properties hold the same value, then from the Apple documentation it seems that using

    - (BOOL)isEqualToNumber:(NSNumber *)aNumber
    

    is the most straightforward and efficient way to compare two NSNumber values.

    For example:

    if ([someNumber isEqualToNumber:someOtherNumber])
    {
        // The numbers hold the same value
    }
    else
    {
        // The numbers hold different values
    }
    

    The documentation also says "This method is more efficient than compare: if you know the two objects are numbers."

    Whenever you need to know whether a value is smaller or greater, they offer the

    - (NSComparisonResult)compare:(NSNumber *)aNumber
    

    method, but personally I would prefer at that point to just pull out the integer values (or double values) and use regular < and > operators to do the comparison, because that makes the code much easier to read, like so:

    if (firstNumber.intValue > secondNumber.intValue)
    {
        // First number is greater than the second number
    }
    else if (firstNumber.intValue == secondNumber.intValue)
    {
        // The two numbers have the same value
    }
    else
    {
        // The first number is smaller than the second number
    }
    

    Something like that is much easier to read than calls to -compare:, in my opinion.

    Erik

    0 讨论(0)
  • 2020-11-30 06:06

    I assume number1 and number2 are pointers to objects. The < sign is comparing the pointers.

    You need to compare the actual floatValue or doubleValue

    if ([number1 doubleValue] < [number2 doubleValue]) 
    

    ....

    0 讨论(0)
  • 2020-11-30 06:08

    NSNumber has a method for comparison: - (NSComparisonResult)compare:(NSNumber*)aNumber

    if([numberOne compare:numberTwo] == NSOrderedSame) 
    {
          // proceed
    }
    
    0 讨论(0)
提交回复
热议问题