NSComparisonResult and NSComparator – what are they?

3 Solutions Collect From Internet About “NSComparisonResult and NSComparator – what are they?”

^ signifies a block type, similar in concept to a function pointer.

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
//          ^                      ^                ^
//   return type of block      type name       arguments

This means that the type NSComparator is a block that takes in two objects of type id called obj1 and obj2, and returns an NSComparisonResult.

Specifically NSComparator is defined in the Foundation Data Types reference.

And to learn more about C blocks, check out this ADC article Blocks Programming Topics.

Example:

NSComparator compareStuff = ^(id obj1, id obj2) {
   return NSOrderedSame;
};

NSComparisonResult compResult = compareStuff(someObject, someOtherObject);

Jacob’s answer is good, however to answer the part about “how is this different than a function pointer?”:

1) A block is not a function pointer. Blocks are Apple’s take on how to make functions first class citizens in C/C++/Objective-C. It’s new to iOS 4.0.

2) Why introduce this strange concept? Turns out first class functions are useful in quite a few scenarios, for example managing chunks of work that can be executed in parallel, as in Grand Central Dispatch. Beyond GCD, the theory is important enough that there are entire software systems based around it. Lisp was one of the first.

3) You will see this concept in many other languages, but by different names. For example Microsoft .Net has lambdas and delegates (no relation to Objective-C delegates), while the most generic names are probably anonymous functions or first class functions.

NSComparisonResult comparisionresult;
NSString * alphabet1;
NSString * alphabet2;


// Case 1

alphabet1 = @"a";
alphabet2 = @"A";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];

if (comparisionresult == NSOrderedSame)
    NSLog(@"a and a are same. And the NSComparisionResult Value is %ld \n\n", comparisionresult);
//Result: a and a are same. And the NSComparisionResult Value is 0

// Case 2
alphabet1 = @"a";
alphabet2 = @"B";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];

if (comparisionresult == NSOrderedAscending)
    NSLog(@"a is greater than b. And the NSComparisionResult Value is %ld \n\n", comparisionresult);
//Result: a is greater than b. And the NSComparisionResult Value is -1

// Case 3
alphabet1 = @"B";
alphabet2 = @"a";
comparisionresult = [alphabet1 caseInsensitiveCompare:alphabet2];

if (comparisionresult == NSOrderedDescending)
    NSLog(@"b is less than a. And the NSComparisionResult Value is %ld", comparisionresult);

//Result: b is less than a. And the NSComparisionResult Value is 1