Huge fan of this website, but it’s my first post!
I’ve got an array of filenames in a directory and I want to sort them. There are hundreds of posts about sorting, but I couldn’t find anything I could use about sorting by modification date.
Here’s my code so far. It successfully creates an array of files that feeds into my tableview. I just need to sort it by modification date, not alphabetically:
//Create dictionary with attributes I care about and a fileList array
NSMutableArray *fileList = [[NSMutableArray alloc] initWithCapacity:10];
NSDictionary *fileData = [NSDictionary dictionaryWithObjectsAndKeys:file, @"file", dateString, @"date", nil];
[fileList addObject:fileData];
//I don't know how to sort this array by the "date" key!
NSArray *files = [fm contentsOfDirectoryAtPath:folderPath error:NULL];
//iterate through files array
for (NSString *file in files) {
NSString *path = [folderPath stringByAppendingPathComponent:file];
//code to create custom object with contents of file as properties
//feed object to fileList, which displays it in the tableview
I’ve read everything I could find online about it, but I just don’t understand how this sorting would work. I understand there are about four different ways to sort, but which one do I chose to sort the array by the date key in the dictionary and how would I implement it here?
Thanks!
EDIT:
Found the answer about 5 seconds after posting this. The code I needed was:
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
[sortedFiles sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
So stupidly easy, I’ve spent all day on this!
Hope this helps someone!
Just to clarify, the answer was: