Jeremy L
Jeremy L

Reputation: 3810

Does Objective-C have an operator, function, or method that can return -1, 0, or 1 when comparing 2 integers or floats?

I tried to search on Google or Stackoverflow but can't find such an operator. In C we used to defined a cmp macro but is there something built in?

Upvotes: 1

Views: 81

Answers (2)

Chris Trahey
Chris Trahey

Reputation: 18290

As @Kashiv mentioned, 100% of C is available in Objective-C. However, if you are using the Cocoa Frameworks and are asking about a more "Cocoa" way of doing it, NSNumber has a compare: method, which returns an NSComparisonResult, which is either -1, 0 or 1.

However, if we are being thoroughly Cocoa in our programming we should further abstract ourselves from the specific knowledge of -1, 0 and 1 and use the constants NSOrderedAscending, NSOrderedSame, and NSOrderedDescending. These are semantically named and that's the real value in programming this way.

NSComparisonResult order = [myInt compare:anotherInt];
switch(order) {
  case NSOrderedAscending:
    // myInt is greater than anotherInt
  break;
  // ... etc
}

Upvotes: 4

akashivskyy
akashivskyy

Reputation: 45180

Anything you can do in C, can be done in Objective-C.

Upvotes: 0

Related Questions