How to sort NSMutableArray of date objects - ios

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.

Related

How to Sort array based on date and time

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:)];

Compare alphanumeric strings in Core Data

I have a core data attribute titled 'gLotNumber' which stores alphanumeric strings. Examples include P1, P5, 7, P10 and 11.
I need to provide a way to search this attribute to the user. The way I can think of providing this is by using NSPredicate on core data using:
[fetchRequest1 setPredicate:[NSPredicate predicateWithFormat:#"(gLotNumber >= 'P1') AND (gLotNumber <= 'P15')"]];
This should result in all entries which start with P and range between 1 to 15. The above code doesn't produce accurate results at all.
Do you know how this can be achieved?
I believe this should work
I don't have a coredata setup hence harcoded some array values.
NSArray *array = #[#{#"gLotNumber":#"P1"},#{#"gLotNumber":#"P15"},#{#"gLotNumber":#"P13"},#{#"gLotNumber":#"P0"},#{#"gLotNumber":#"11"},#{#"gLotNumber":#"10"},#{#"gLotNumber":#"P31"},#{#"gLotNumber":#"P013"},#{#"gLotNumber":#"16"},#{#"gLotNumber":#"P38"}];
NSArray *filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF.gLotNumber BEGINSWITH 'P' AND SELF.gLotNumber <= 'P15'"]];
NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:#"gLotNumber" ascending:YES comparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSArray *sorted = [filtered sortedArrayUsingDescriptors:#[desc]];
You can set the sort descriptor and predicate to the fetch request Hope this helps

Sorting NSMutableArray with date in ios7

hi i am new in IOS i have one array name with array1. Each index of an array there is one dictionary with 4 different fields like name,date,marks,standard. these all values are in NSString format. i want to sort this array1 by date. so can any one help me to do this please
here below is some part of my code
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
NSString *myname = name.text;
NSString *marks= marks.text;
NSString *date=date.text;
NSString *address=address.text;
NSString *rID=rID.text;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyMMdd"];
NSDate *date1 = [dateFormat dateFromString:date];
[tempDict setObject:myname forKey:#"name"];
[tempDict setObject:marks forKey:#"marks"];
[tempDict setObject:date1 forKey:#"date"];
[tempDict setObject:address forKey:#"address"];
[tempDict setObject:rID forKey:#"Rid"];
[array1 addObject:tempDict];
NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:#"date"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByDate];
NSArray *sortedArray = [array1 sortedArrayUsingDescriptors:sortDescriptors];
If you want to sort your array with the date then you have to create NSDate object instead of NSString
NSDate *date = [dateFormatter dateFromString:date.text];
where dateFormatter is your NSDateFormatter
I think -sortUsingComparator: is the cleanest option.
[array1 sortUsingComparator: (id obj1, id obj2) {
return [[obj1 objectFoKey: #"date"] compare: [obj2 objectForKey: #"date"]];
}];
I dont know about the size of your array but if it is not something very big, you can do this:
make a dictionary (we call it sortingDict) with number of index (in array1) as key and your date of the corresponding array object as the value. You should iterate through your array1 to do this of course. (it would be better if you create NSDate objects of your string dates by the way).
get sortingDict all values. ([sortingDict allValues]) We call this dateArray.
sort your date array using NSSortDescriptor or any other algorithm you may want to use. We call it sortedDateArray.
now in a for loop iterating through sortedDateArray you get the keys of your sortingDict in order (You can use [sortingDict allKeysForObject:] and put it in an array sortedIndices
now you have an array with indices of array1 in your desired sorted order.
reordering your initial array1 wouldn't be a problem I believe.
P.S: This is a very inefficient way that just got out of the top of my head, hope it helps.
you can do like this.. if you wanted to display in tableview than other arrays are useful.
if(array1 > 0)
{
NSMutableArray *UniqueDates = [array1 valueForKeyPath:#"#distinctUnionOfObjects.date"];
[recordDates addObjectsFromArray:UniqueDates];
NSArray *cleanedArray = [[NSSet setWithArray:recordDates] allObjects];
recordDates = [cleanedArray mutableCopy];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:NO];
[recordDates sortUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];
[mainarray addObjectsFromArray:array1];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"date == %#", [recordDates objectAtIndex:YourIndex]];
// yourindex == indexpath.row if you are displaying in table view
NSArray *filterContacts= [array1 filteredArrayUsingPredicate:predicate];
mainarray = [filterContacts mutableCopy];
recordDates and mainarray is also mutablearray.

Getting the dictionary with the most recent date from an array of dictionaries

I have an array of dictionaries. These dictionaries have a format like this:
NSDictionary *oneDict = #{
#"code": #"123"
#"name": #"car"
#"date": creationDate
}
these dictionaries are stored in a NSArray.
I need to extract the dictionary with the most recent date from that array.
I can discover the most recent date by doing this:
NSArray *extractDates = [array objectForKey:#"date"];
NSArray sortedDates = [extractDates sortedArrayUsingSelector:#selector(compare:)];
NSDate *mostRecentDate = (NSDate *)[sortedDates lastObject];
Now I know, I can interact over the array and look for that date, so I can get the dictionary, but I wonder if Objective-C has some sort of mechanism that can do that directly.
Try this,
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
sortDescriptorWithKey:#"date"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedArray = [array
sortedArrayUsingDescriptors:sortDescriptors];
NSDictionary *dict = (NSDictionary *)[sortedArray lastObject];

NSMutableArray of NSMutableDictionary how to filter using regex

I am new to ios.
I have a NSMutableArray of NSDictionary. How can I filter the array?
//sections is a NSMutableArray of NSMutableDictionary elements
[sections addObject:getName];
NSSortDescriptor *sortDescriptorFirst = [NSSortDescriptor sortDescriptorWithKey:#"first" ascending:YES];
NSSortDescriptor *sortDescriptorLast = [NSSortDescriptor sortDescriptorWithKey:#"last" ascending:YES];
NSSortDescriptor *descriptor=[NSArray arrayWithObjects:sortDescriptorFirst,sortDescriptorLast,nil];
NSArray *sortedArray =[sections sortedArrayUsingDescriptors:descriptor];
How to continue the code from here in order to match the array with the regex value?
If I understand your question correctly, you need a string that contains all
values of a dictionary. That would be:
NSString *str = [[dict allValues] componentsJoinedByString:#" "];
and then you can check if str matches the given regex pattern as before.
Ok from the look of your post it looks like you can just use an NSPredicate instead of a RegEx
try something along the lines of this:
NSPredicate* p = [NSPredicate predicateWithFormat:#"key = %#", value];
NSArray* matches = [arrayOfDicts filteredArrayUsingPredicate:p];
NSPredicate can use all sorts of operators such as LIKE, !=, and <
if you need to filter based on a value being in a list you can construct a predicate along the lines of #"key IN %#", arrayOfPossibleValues
replace key in that sample code with the key in the dictionary you are trying to filter by. you can filter using multiple keys if needed.

Resources