Objectiv C: Dateien nach Datum sortieren / sort files by date

Ein kleiner Codeschnipsel um Dateien in einem Array nach Datum zu sortieren:

NSString *documentsDirectory = @"XXX"; //path to the files
NSArray *dirContents;
dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil]; //save file-names to the array

//sort function
NSComparisonResult dateSort(NSString *f1, NSString *f2, void *context) {
NSString *documentsDirectory = @"XXX"; //path to the files

NSString *p1 = [NSString stringWithFormat:@"%@/%@", documentsDirectory, f1];
NSString *p2 = [NSString stringWithFormat:@"%@/%@", documentsDirectory, f2];

NSFileManager *fm2 = [[NSFileManager alloc] init];
return [[[fm2 fileAttributesAtPath:p2 traverseLink:YES] objectForKey:NSFileModificationDate] compare: [[fm2 fileAttributesAtPath:p1 traverseLink:YES] objectForKey:NSFileModificationDate]];

[fm2 release];
}

dirContents = [dirContents sortedArrayUsingFunction:dateSort context:NULL];

Kommentieren