How to Sort array based on date and time - ios

i have date string in form of "yyyy-MM-dd HH:mm" i have some 100 obhjects in an array with different date and time.now my question is how to sort this array based on time and date, i tried in many ways but no use .can any one help me .thanks in advance

used this method for sort an array.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortArrayUsingDescriptors:#[sortDescriptor]];
May be help for you

If you have an array of strings, take advantage of your date format and just sort it lexically.
NSArray* sorted = [dates sortedArrayUsingComparator:^(NSString* a, NSString* b) {
return [a compare:b];
}];
If you actually have an array of NSDate objects, use the NSDate compare functions, using almost identical code (compare: works to compare two homogenous data types in many cases)
NSArray* sorted = [dates sortedArrayUsingComparator:(NSDate* a, NSDate* b) {
return [a compare:b];
}];
With the simplicity of the comparator, you can actually just use the selector directly:
NSArray* sorted = [dates sortedArrayUsingSelector:#selector(compare:)];

Related

Objective-C, Sorting an NSMultable array of type class, alphabetically?

I'm trying to sort a property on a type of a mutable array.
However I've only managed to sort a NSString array.
NSMutableArray<DBFILESFileMetadata*> *tmpArray = [[NSMutableArray alloc]init];
for (DBFILESMetadata *entry in entries)
{
//conditions
[tmpArray addObject:fileMetadata];
}
Here's the type / class
https://github.com/dropbox/dropbox-sdk-obj-c/blob/4c99bdf726cf9724adfddc19e71a87a6012eddeb/Source/ObjectiveDropboxOfficial/Shared/Generated/ApiObjects/Files/Headers/DBFILESMetadata.h
I've tried
[yourArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
and
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
The property is called name.
I've seen answer like this How can I sort an NSMutableArray alphabetically? but I can't seem to get this to work for my scenario.
In order to sort using sortUsingSelector you need to implement your compare method in the objects that you are trying to compare. (So your DBFILESMetadata class would need a compare method - localizedCaseInsensitiveCompare in the code above.)
You should be able too use a sort descriptor as you show in your second attempt. What happens when you do that?
A third way to do it is to use the NSMutableArray sortUsingComparator and write an NSComparator block that compares the 2 objects.
I'm out of practice with Objective-C but a quick Google search found an example, which I adapted to your specific problem:
[entries sortUsingComparator:
^NSComparisonResult(DBFILESMetadata *obj1, DBFILESMetadata *obj2)
{
return [obj1.name localizedCaseInsensitiveCompare: obj2.name];
}];
That should work, although as I say I'm out of practice in Objective-C, and its block syntax is pretty awkward and counter-intutive.

Sorting the dates in an array?

In my application I have an array of strings representing the dates in the Format MM/dd/YYYY
and below is the code I used to sort this array
NSDateFormatter *formatter =[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/YYYY"];
NSLog(#" arr %#",arr);
[arr sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSDate *date1=[formatter dateFromString:obj1];
NSDate *date2=[formatter dateFromString:obj2];
return [date1 compare:date2];
}];
NSLog(#" arr %#",arr);
below is the output of nslog
2013-04-08 17:23:48.112 SEEMR[2792:c07] arr (
"02/18/2013",
"02/16/2013",
"02/14/2013",
"01/16/2013",
"02/13/2013",
"03/16/2013"
)
2013-04-08 17:24:07.662 SEEMR[2792:c07] arr (
"02/18/2013",
"02/16/2013",
"02/14/2013",
"01/16/2013",
"02/13/2013",
"03/16/2013"
)
But it is not sorting as expected so help me peers
When using NSDateFormatter, always test if your formatting string is correct. Yours isn't. It should be MM/dd/yyyy (the case is important).
In other words, since your formatter works incorrectly, all dateFromString: return nil and you are always comparing nil with a nil, which returns 0.
Saving your dates as a NSDate instances would make your life easier. In general, it's better to convert the date into NSString only if you are presenting it to the user or sending it to some other application (e.g. web service).
You can do something like this:
NSSortDescriptor* sortByDate = [NSSortDescriptor sortDescriptorWithKey:#"date property name" ascending:YES];
[mutableArray sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];
Hope it helps!

How to sort by greatest and less than in iOS

I have values from 200 to 1 stored as strings in an array called beaus.
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:#"dataoflar" ascending:NO];
[beaus sortUsingDescriptors:#[sortDesc]];
However, this only sorts them by the first number (2 is above 10). Is there any way to sort by amount?
You can update your sort description like this:
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:#"dataoflar.integerValue" ascending:NO];
[beaus sortUsingDescriptors:#[sortDesc]];
This will get the integer value of each string and the sort will be based on that number instead of the string value.
Assuming it doesn't matter that the values are NSStrings in the final array you should sort it like this
NSMutableArray *mutableBeaus = [[beaus mutableCopy] autorelease];
[mutableBeaus sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
// mutableBeaus now has the array sorted in an ascending order 1 < 002 < 3
If for some reasons you don't want to convert the Strings to int during import, you
have to write and use your own Sorter:
This shows how to sort beause by property "datatoflat" of type NSString which contain number. Sort is done ascending. For descending exchange the last line to return (i1- i2).
NSArray *sortedArray;
sortedArray = [beaus sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString* s1 = [(NSString*) a dataoflar];
NSString* s2 = [(NSString*) b dataoflar];
int i1 = [s1 integerValue];
int i2 = [s2 integerValue];
return (i2 - i1);
}];
If you have to use strings, then left fill you numbers with zeros, then it will sort like you want with not other changes, like this:
'002' instead of '2' and '034' instead of '34'

How to sort NSMutableArray of date objects

I'm doing some small work on sorting the date strings in the NSMutableArray, i'm getting the array from the sqlite db.
If you print the array it is showing like this
date strings are (
"2011-05-01",
"2011-02-01",
"2012-01-08",
"2012-05-08",
"2010-01-09
)
I want to show the dates in ascending order. Please help me out guys..... I'm newbie to objc..
First you should convert all date Strings (which is NSString) objects to NSDate objects and then sort these dateObjects.
I believe you have dateArray containing all those strings.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self"
ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
OR
NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator:
^(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
If your dates are really strings in the format YYYY-mm-dd, as in your question, then this will sort them in ascending order:
[arrayOfDates sortUsingSelector:#selector(compare:)];
That will also work if your dates are actually NSDate objects.
If you want to create a sorted copy of the array:
NSArray *sortedArray = [arrayOfDates sortedArrayUsingSelector:#selector(compare:)];
Sorting should be done, imo, by the database, in general. sqlite3 does support order by.

NSSortDescriptor sort a string field as a number with comparator block not working

I have a field full of ids from a third party. The ids are numbers but written to the db as a string.
I want to sort a fetch sorted by this id on the value of the integer. So I'm adding this NSSortDescriptor to the NSFetchRequest.
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:#"someId" ascending:YES comparator:^(id a, id b) {
return [[numFormatter numberFromString:a] compare:[numFormatter numberFromString:b]];
}];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortBy]];
But I get results like the the following. These are still sorted as a string, alphabetically.
730275292
73900038
730172867
7350727
830138437
835164
837287901
8338804
930274
9324376
What am I not understanding about using this comparator block?
EDIT May 1 2012 9:20 AM EST
To test whether the comparator block is being used, I tried the following to sort based on the length of the field.
NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:#"fbId" ascending:YES comparator:^(id a, id b) {
if ([a length] < [b length]) {
return NSOrderedAscending;
} else if ([a length] > [b length]) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortBy]];
I'm still getting results sorted by the alphabetically order! So this makes me think the comparator block is not even being used.
716164250
726354466
73900038
739600038
7450727
810138437
801164
801375346
8213997
Try this !
[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(localizedStandardCompare:)]
I don't use NSFetchRequest so I can't comment on that specifically, but it appears to be something related to it. The code you use in your comparator block is just fine. I setup an array of the exact numbers you show and then sorted them using your code and everything worked out fine:
NSArray *array = [NSArray arrayWithObjects:#"730275292",
#"73900038",
#"730172867",
#"7350727",
#"830138437",
#"835164",
#"837287901",
#"8338804",
#"930274",
#"9324376", nil];
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSArray *sArray = [array sortedArrayUsingComparator:^(id a, id b) {
return [[numFormatter numberFromString:a] compare:[numFormatter numberFromString:b]];
}];
NSLog(#"%#",sArray);
When the above code runs, I get a log of:
(
835164,
930274,
7350727,
8338804,
9324376,
73900038,
730172867,
730275292,
830138437,
837287901
)
I believe this is the order you're looking for. You might consider taking the results of your fetch request and sorting them in an array after you've received them. I doubt it matters whether an array does the sorting or the fetch request does the sorting. Most likely there's no performance gain of using one over the other.
If you still want NSFetchRequest to do the sorting, then there might be something your missing in order to get it to sort properly. Honestly, I'm not sure since I've not used it.
UPDATE
Quickly looking through the NSFetchRequest docs, I've found that there are some parameters that affect sorting. For example, in the docs for the resultType it gives this message:
You use setResultType: to set the instance type of objects returned
from executing the request—for possible values, see
“NSFetchRequestResultType.” If you set the value to
NSManagedObjectIDResultType, this will demote any sort orderings to
“best efforts” hints if you do not include the property values in the
request.
So it looks as though the return type might be affecting your sorting.

Resources