Comparison of NSNumber Literals

I really like the new literals in Objective-C. I am wondering if new additions have a better way to compare numbers.

For example, if I want to compare a and b :

 a = @1; b = @2; 

This is the only way to compare them as follows:

 [a intValue] > [b intValue] 

Or are there better, more elegant solutions?

+6
source share
4 answers

For equality checks you can use isEqualToNumber , which checks if either id or content is equal (with the latter using compare ):

 if ([a isEqualToNumber:b]) // if a == b 

I don’t know why they also did not implement the convenience methods isGreaterThanNumber and isLessThanNumber (and possibly >= and <= ), since the compare method below looks a bit awkward.

To check for inequality, simply use compare directly (you can also do this for equality, as can be seen from the first below):

 if ([a compare:b] == NSOrderedSame) // if (a == b) if ([a compare:b] == NSOrderedAscending) // if (a < b) if ([a compare:b] == NSOrderedDescending) // if (a > b) if ([a compare:b] != NSOrderedSame) // if (a != b) if ([a compare:b] != NSOrderedAscending) // if (a >= b) if ([a compare:b] != NSOrderedSescending) // if (a <= b) 

Details can be found on the NSNumber class documentation page .


Keep in mind that nothing prevents you from creating your own helper function, which, for example, would allow you to use the code:

 if (nsnComp1 (a, ">=", b)) ... // returns true/false (yes/no) 

or

 if (nsnComp2 (a, b) >= 0) ... // returns -1/0/+1 

although it is less than Objective-C and more than C :-) It depends on whether your definition of elegance is mainly related to efficiency or readability. Is it possible that your intValue option is preferable - this is a decision that you will need to make yourself.

+13
source

NSNumber implements -compare: (like a number of other classes). So you can say

 switch ([a compare:b]) { case NSOrderedAscending: // a < b // blah blah break; case NSOrderedSame: // a == b // blah blah break; case NSOrderedDescending: // a > b // blah blah break; } 
+7
source

NSNumber also has isEqualToNumber:

0
source

Here is a snippet of code to check which ones work well:

 NSLog(@"%d", number1 == number2); NSLog(@"%d", [number1 isEqual:number2]); NSLog(@"%d", [number1 isEqualToNumber:number2]); 

Exit:

 1 1 1 

Conclusion:

To understand the comparison, you need to understand the distribution of instances. NSNumber internally implements the cache of objects assigned, and maps existing objects to any newly created objects using values. If the found NSNumber is found with a value of 1, no new instance of NSNumber is created.

0
source

Source: https://habr.com/ru/post/925075/


All Articles