Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSComparisonResult and NSComparator - what are they?

What is NSComparisonResult and NSComparator?

I've seen one of the type definitions, something like that:

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);

Is it any different from a function pointer?

Also, I can't even guess what the ^ symbol means.

like image 688
wh1t3cat1k Avatar asked Nov 07 '10 15:11

wh1t3cat1k


2 Answers

^ 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);
like image 127
Jacob Relkin Avatar answered Sep 21 '22 14:09

Jacob Relkin


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.

like image 44
whitneyland Avatar answered Sep 22 '22 14:09

whitneyland