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.
^
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With