2012-10-10 82 views
0

我有NSMutableArray包含NSArray對象,它看起來像這樣NSMutableArray的排序任務

(
    "2012-10-10 13:13:29 +0000", 
    cc5772389efc1f93bedaab872bad542a1c8432af, 
    "{\n size    = {360, 480}\n CGImage.size  = {480, 360}\n imageOrientation = UIImageOrientationRight\n}" 
), 
    (
    "2012-10-10 13:13:37 +0000", 
    6c09d99f940af8e7d1d1392d28abee2133b7ac75, 
    "{\n size    = {360, 480}\n CGImage.size  = {480, 360}\n imageOrientation = UIImageOrientationRight\n}" 
), 
    (
    "2012-10-10 13:13:19 +0000", 
    0165776bd9e96e640c905471ddb8630c22a8911c, 
    "{\n size    = {360, 480}\n CGImage.size  = {480, 360}\n imageOrientation = UIImageOrientationRight\n}" 
) 

NSArray對象包含的第一個指數NSDate對象,我想從舊到最新排序此NSMutableArray

有什麼想法嗎?

回答

4

可以使用的NSMutableArray的-sortUsingComparator:

sortUsingComparator:
排序使用由給定NSComparator塊中指定的比較方法的陣列。

- (void)sortUsingComparator:(NSComparator)cmptr
參數cmptrcomparator塊。

[array sortUsingComparator: ^(NSArray *array1, NSArray *array2) { 
    NSDate *date1 = [array1 objectAtIndex:0]; 
    NSDate *date2 = [array2 objectAtIndex:0]; 
    return [date1 compare:date2]; 
}]; 

顛倒順序,你可以簡單地返回[date2 compare:date1]

0

使用-sortedArrayUsingFunction:context:

NSInteger dateSort(id obj1, id obj2, void *context) 
{ 
    NSData *date1 = [obj1 objectAtIndex:0] ; 
    NSData *date2 = [obj2 objectAtIndex:0] ; 
    return [date1 compare:date2]; 
} 
NSArray *sortedArray = [array sortedArrayUsingFunction:dateSort context:NULL]; 
+0

有什麼不對這種做法? –