[英]Sort objects based on a NSString date
我有一個對象數組,每個對象都包含一個expectedDeliveryDate
字符串。 我有一個采用日期字符串並將其轉換為NSDate
。
如何將它們按升序或降序排序?
我假設您有一個Array,其中每個對象都是Dictionary,並且其中包含傳遞數據
試試這個,我在我的項目中創建此方法,以使用Key對數組進行排序。
在此方法中,lastDescriptor具有選擇器compare:因此,兩個日期將在此方法中進行比較和自動排序。
-(NSMutableArray *)sortArrayWithKey:(NSString *)sortingKey andArray:(NSMutableArray *)unsortedArray{
NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:sortingKey ascending:NO selector:@selector(compare:)];
NSArray *descriptors = [NSArray arrayWithObjects: lastDescriptor, nil];
return [unsortedArray sortedArrayUsingDescriptors:descriptors].mutableCopy;
}
希望這對您也有幫助。
+ (void)filterAlertsByTime:(NSMutableArray*)alerts {
NSDateFormatter *hourFormatter = [[NSDateFormatter alloc] init];
[hourFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
[alerts sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = [hourFormatter dateFromString:[NSString stringWithFormat:@"%@",obj1[@"expectedDeliveryDate"]]];
NSDate *date2 =[hourFormatter dateFromString:[NSString stringWithFormat:@"%@",obj2[@"expectedDeliveryDate"]]] ;
return [date1 compare:date2];
}];
}
請根據ExpectedDeliveryDate字符串的格式編輯日期格式
使用NSString日期對數組進行排序。
完成的事情:
嘗試這個
NSMutableArray *oldArray; //Array which consist of object with date as string.
NSMutableArray *newArray = [[NSMutableArray alloc] init];
if(oldArray.count!=0){
//CONVERT STRING TO DATE
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM d, yyyy"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
for (int i=0 ;i<oldArray.count;i++)
{
NSMutableDictionary *dict= [oldArray objectAtIndex:i];
NSString *stringDate = [dict objectForKey:@"stringDateKey"];
if(![stringDate isEqualToString:@""]){
NSDate *date = [dateFormat dateFromString:stringDate];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
[newDict addEntriesFromDictionary:dict];
[newDict setObject:date forKey:@"newDate"];
[newArray addObject:newDict];
}
else{
[newArray addObject:dict];
}
}
//SORTING THE ARRAY
NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"newDate" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
NSArray *sortedArray = [dataValue sortedArrayUsingDescriptors:sortDescriptors];
}
您可以使用排序描述符按對象的日期對其進行排序。 因此,首先將字符串轉換為NSDates並將其設置在自定義對象的另一個屬性上,然后以這種方式對其進行排序。
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"expectedDeliveryDate"
ascending:YES];
NSArray *sortedDeliverDates = [deliveryItems sortedArrayUsingDescriptors:@[descriptor]];
此外,NSDate還具有compare:方法,該方法可讓您比較兩個日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.