compare

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"White",@"Blue",@"Red",@"Black",nil];
    [array sortUsingSelector:@selector(compare:)];
    NSLog(@"sorted array:%@",array);
運行結果是:sorted array:(
    Black,
    Blue,
    Red,
    White
)
很顯然,這裏是按照ascii碼來進行排序的。compare:的方法並沒有編寫。可以在幫助文檔裏找到一個函數
compare:
Returns the result of invoking compare:options:range: with no options and the receiver’s full extent as the range.

- (NSComparisonResult)compare:(NSString *)aString
Parameters
aString
The string with which to compare the receiver.
This value must not be nil. If this value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
The result of invoking compare:options:range: with no options and the receiver’s full extent as the range.

Discussion
If you are comparing strings to present to the end-user, you should typically use localizedCompare: or localizedCaseInsensitiveCompare: instead.

這個方法會調用compare:options:range:的方法,並且後兩個參數都是默認的值,返回值就是一個NSComparisonResult類型,也就是前面說過的說明receiver和sender兩個參數的比較結果。

在調用sortUsingSelector()方法時,我們指定使用compare:方法來進行比較。它內部可能使用了類型來進行判斷,因爲這裏比較的類型是NSString,所以會調用NSString 的compare:方法。排序的過程是不可見的,但是過程就是:取出各個元素,使用compare:比較,然後放到合適的位置。

因爲NSString 類的擴展(category)中規定好了這個compare:方法,也就是說通過這個方法,已經知道了如何判定A 字串和B字串誰比較大,但是在我們自己定義好的類中,這樣的compare方法需要自己來指定一個(比如我們定義一個Sudent的類型,然後規定排序的時候按照ID來排)。我把lz例子中的幾個重要方法註釋一下,幫助理解:

@interface AddressBook: NSObject <NSCopying,NSCoding>
{
    NSString *bookName;
    NSMutableArray *book; //用來存儲AddressCard對象的可變數組
}

@implementation AddressCard

@synthesize name,email; //name爲AddressCard 的一個成員,並作爲屬性提供

-(NSComparisonResult) compareNames: (id)element;
{
    return [name compare:[element name]]; //返回當前的name和傳入參數element的屬性name比較後的結果
                                                                        //因爲name是NSString類型的,所以這個compare:方法是調用NSString 的compare方法
                                                                        //很顯然,element應該也是一個AddressCard類型的對象
}

-(void)sort
{
    [book sortUsingSelector:@selector(compareNames:)]; //sort方法,book中存儲着所有的AddressCard類型對象
                                                                                               //比較的方式就是調用compareNames:的方法
}

下面說一下排序的過程,假設現在book中只有兩個元素,book1和book2, 它們的name屬性值分別爲@"The C Programming Language"和@"Beginning iPhone 4 Development",調用sortUsingSelector:方法後,操作如下:
1. 取出array中的book1
2. 調用 book1的compareNames:方法,把book2當作參數傳入,比較兩者的大小
3. 在compareNames:的內部,book1的name屬性(因爲是book1是receiver,因此這裏的name就是它的成員)和book2的name(通過element傳入book2對象)比較的返回值作爲結果。這裏是做NSString類型的比較,所以返回值應該是NSOrderedDescending(ascii 的值比對)。
4. 因爲返回值說明,第一個元素比第二個元素要大,因此array中的兩個元素會做位置的調換。
結束

當然,數組中的元素可能有多個,所以根據不同的排序方式,取元素比對的過程、移動元素的過程會不太一樣(冒泡、堆排、快排)。但是使用這種方式是不需要關心的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章