7

什麼是NSComparisonResultNSComparatorNSComparisonResult和NSComparator - 它們是什麼?

我見過的類型定義的一個,類似的東西:

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

它是從一個函數指針有什麼不同?

此外,我什至不能猜測什麼^符號的含義。

回答

22

^表示塊類型,概念上類似於函數指針。

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

這意味着該類型NSComparator,取入稱爲obj1obj2id類型的兩個對象,並返回一個NSComparisonResult

具體的NSComparator定義在Foundation Data Types reference

要了解有關C塊的更多信息,請查看此ADC文章Blocks Programming Topics

例子:

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

NSComparisonResult compResult = compareStuff(someObject, someOtherObject); 
+0

非常感謝Jacob!現在我已經發現了關於塊的教程並學習了更多) – wh1t3cat1k 2010-11-07 20:32:51

7

雅各布的回答是不錯的,但回答部分關於「這怎麼不是函數指針有什麼不同?」:

1)塊是功能指針。塊是蘋果公司在C/C++/Objective-C中如何製作一等公民的功能。這是iOS 4.0的新功能。

2)爲什麼要引入這個奇怪的概念?原來,第一類函數在很多情況下都很有用,例如管理可以並行執行的工作塊,就像在Grand Central Dispatch中那樣。除了GCD之外,這個理論足夠重要,以至於整個軟件系統都以它爲基礎。 Lisp是第一個。

3)您將在許多其他語言中看到這個概念,但用不同的名稱。例如Microsoft .Net有lambda和代表(與Objective-C代表無關),而最通用的名稱可能是匿名函數或first class functions

-1
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 
相關問題