Comparing NSNumbers in Objective-C

I'm new to Obj-C, and I'm a little confused about this scenario. I have the following code:

if (number1 < number2) { NSLog(@"THE FOLLOWING NUMBER "); NSLog(@"%@", number1); NSLog(@"IS LESS THAN"); NSLog(@"%@", number2); } 

When I run this code, I see really strange results:

 2011-07-06 20:38:18.044 helloworld[1014:207] THE FOLLOWING NUMBER 2011-07-06 20:38:18.047 helloworld[1014:207] 190.8776 2011-07-06 20:38:18.050 helloworld[1014:207] IS LESS THAN 2011-07-06 20:38:18.053 helloworld[1014:207] 96.75866 

Both numbers are NSNumber objects, how could something like this happen? I get two numbers, finding the distance between the sprites on the screen.

Any hints or tips would really be appreciated

+48
objective-c nsnumber
Jul 07 2018-11-11T00
source share
4 answers

I assume that number1 and number2 are pointers to objects. <sign compares pointers.

You need to compare the actual value of floatValue or doubleValue

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

....

+91
Jul 07 2018-11-11T00:
source share

In cases where you just want to check if two NSNumber properties have the same value, from the Apple documentation it seems like using

 - (BOOL)isEqualToNumber:(NSNumber *)aNumber 

is the easiest and most 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 comparison: if you know that two objects are numbers."

Whenever you need to know less or more value, they offer

 - (NSComparisonResult)compare:(NSNumber *)aNumber 

but personally, I would prefer at this point to just pull out the integer values ​​(or double values) and use regular <and> for comparison, because it makes the code much easier to read, for example:

 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 this is much easier to read than calls to -compare :, in my opinion.

Eric

+33
Jan 23 '14 at 2:12
source share

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

 if([numberOne compare:numberTwo] == NSOrderedSame) { // proceed } 
+15
Nov 07 '13 at 11:40
source share

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
May 11 '17 at 8:11
source share



All Articles