I have an NSMutableArray
, and I want to sort it by date, descending.
The date looks like:
Fri, 07 Dec 2012 08:40:33 +0100
I have an NSMutableArray
, and I want to sort it by date, descending.
The date looks like:
Fri, 07 Dec 2012 08:40:33 +0100
If you have only dates in array then it can be sort by:
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
Or using blocks
NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator:
^(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
EDIT:
As per discussion please check the code :
Assumimg you have a class having these properties :
//MyClass.h
@interface MyClass : NSObject
@property(strong) NSString *title;
@property(strong) NSString *description;
@property(strong) NSDate *pubDate;
@end
//MyClass.m
@implementation MyClass
- (id)init
{
self = [super init];
if (self) {
_title=[NSString new];
_description=[NSString new];
_pubDate=[NSDate new];
}
return self;
}
-(NSComparisonResult)comparePubDate:(MyClass *)pd{
return [_pubDate compare:[pd pubDate]];
}
@end
In your class where you have array of objects
In .h
@property(strong) NSMutableArray *myClassObjects;
In .m
-(NSDate *)dateInMyFormat:(NSString *)dateString{
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"EN"]];
NSDate *myDate=[dateFormatter dateFromString:dateString];
return myDate;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
MyClass *obj1=[MyClass new];
[obj1 setTitle:@"obj1 title"];
[obj1 setDescription:@"obj1 description"];
[obj1 setPubDate:[self dateInMyFormat:@"Fri, 07 Dec 2012 08:40:33 +0100"]];
MyClass *obj2=[MyClass new];
[obj2 setTitle:@"obj2 title"];
[obj2 setDescription:@"obj2 description"];
[obj2 setPubDate:[self dateInMyFormat:@"Fri, 08 jan 2012 08:40:33 +0100"]];
MyClass *obj3=[MyClass new];
[obj3 setTitle:@"obj3 title"];
[obj3 setDescription:@"obj3 description"];
[obj3 setPubDate:[self dateInMyFormat:@"Fri, 08 jan 2012 06:40:33 +0100"]];
MyClass *obj4=[MyClass new];
[obj4 setTitle:@"obj4 title"];
[obj4 setDescription:@"obj4 description"];
[obj4 setPubDate:[self dateInMyFormat:@"Fri, 01 Jan 2012 08:40:33 +0100"]];
[_myClassObjects addObject:obj1];
[_myClassObjects addObject:obj2];
[_myClassObjects addObject:obj3];
[_myClassObjects addObject:obj4];
for (MyClass *object in _myClassObjects) {
NSLog(@"Title:%@, %@, %@",object.title, object.description, object.pubDate);
}
//for sorting
NSArray *sortedArray=[_myClassObjects sortedArrayUsingSelector:@selector(comparePubDate:)];
_myClassObjects=(NSMutableArray *)sortedArray;
NSLog(@"After sorting");
for (MyClass *object in _myClassObjects) {
NSLog(@"Title:%@, %@, %@",object.title, object.description, object.pubDate);
}
}