![](/img/trans.png)
[英]Sorting an NSArray of Objects WRT the objects contained in NSSet in those objects
[英]Sorting Objects in NSArray
我有一個NSArray,里面有3個對象。 每個對象由5個值組成。 如何在對象中按日期排序?
result: (
gg,
"2012-10-28 01:34:00 +0000",
"Church Bells",
"pin_red",
1
)(
iu,
"2008-09-22 17:32:00 +0000",
"Birthday Song",
"pin_red",
1
)(
"my birthday woo hoo",
"2012-09-04 19:27:00 +0000",
"Birthday Song",
"pin_blue",
1
)
我正在尋找的結果 - Sorted Array應該是這樣的。
(
iu,
"2008-09-22 17:32:00 +0000",
"Birthday Song",
"pin_red",
1
)
(
"my birthday woo hoo",
"2012-09-04 19:27:00 +0000",
"Birthday Song",
"pin_blue",
1
)
(
gg,
"2012-10-28 01:34:00 +0000",
"Church Bells",
"pin_red",
1
)
我從我的nsdictionary對象獲取此數組。
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:stringsPlistPath];
stringsMutableArray = [[NSMutableArray alloc] initWithObjects:nil];
for (id key in dictionary)
{
[stringsMutableArray addObject:[dictionary objectForKey:key]];
}
嘗試這個:
NSArray *sortedArray = [result sortedArrayUsingComparator: ^(id obj1, id obj2) {
NSArray *arr1 = (NSArray *)obj1;
NSArray *arr2 = (NSArray *)obj2;
NSDate *date1 = arr1[1];
NSDate *date2 = arr2[1];
return [date1 compare:date2];
}];
此代碼假定您實際上有一個數組數組,並且日期是NSDate對象始終在內部數組中的索引1處。 如果按照您想要的相反順序排序,請將兩個日期交換為日期比較。
這是一個解決您問題的類似問題: 對日期字符串或對象進行NSArray排序
我將粘貼以下鏈接的答案:
將日期作為NSDate對象存儲在NS(Mutable)數組中,然后使用[
-[NSArray sortedArrayUsingSelector:
] [1]或[-[NSMutableArray sortUsingSelector:]
] [1]並傳遞@selector(compare:)
作為參數。 [-[NSDate compare:]
] [2]方法將按升序為您排序日期。 這比創建NSSortDescriptor簡單,並且比編寫自己的比較函數簡單得多。 (NSDate對象知道如何將自己相互比較,至少與我們希望使用自定義代碼一樣有效。)[1]: http : //developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingSelector :[2]: http: //developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare :
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.