NSComparisonResult
和NSComparator
是什么?
我见过一个类型定义,大概是这样的:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
它和函数指针有什么不同吗?
此外,我甚至无法猜测出^
符号的含义。
NSComparisonResult
和NSComparator
是什么?
我见过一个类型定义,大概是这样的:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
它和函数指针有什么不同吗?
此外,我甚至无法猜测出^
符号的含义。
^
表示一个块类型,与函数指针类似。
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
// ^ ^ ^
// return type of block type name arguments
这意味着类型 NSComparator
是一个块(block),它接受两个类型为 id
的对象,称为 obj1
和 obj2
,并返回一个 NSComparisonResult
值。
具体而言,NSComparator
定义在Foundation 数据类型参考文档中。
有关 C 块的更多信息,请查看此 ADC 文章:块编程主题。
示例:
NSComparator compareStuff = ^(id obj1, id obj2) {
return NSOrderedSame;
};
NSComparisonResult compResult = compareStuff(someObject, someOtherObject);
Jacob的回答很好,但是针对“这与函数指针有何不同?”这部分的回答:
1)块(Block)不是函数指针。块是苹果公司对如何使C/C++/Objective-C中的函数成为一等公民的看法。它是iOS 4.0中的新概念。
2)为什么要引入这个奇怪的概念?事实证明,一等公民函数在许多场景下都非常有用,例如管理可以在并行执行的工作块,就像Grand Central Dispatch一样。除了GCD之外,这个理论也非常重要,因此有整个软件系统基于它。Lisp是最早的之一。
3)您将在许多其他语言中看到这个概念,但名称不同。例如,Microsoft .Net具有lambda和delegate(与Objective-C delegate无关),而最通用的名称可能是匿名函数或一等公民函数。
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