Here's an example of how to do it. This approach gets an array of files from the NSFileManager
, then sorts that array based on the NSURL
property NSURLContentModificationDateKey
.
I missed the iPhone tag the first time. I've changed the code to work with the iPhone SDK.
NSInteger lastModifiedSort(id path1, id path2, void* context)
{
return [[path1 objectForKey:@"lastModDate"] compare:
[path2 objectForKey:@"lastModDate"]];
}
-(void)filesByModDate
{
NSString* path = @"/";
NSError* error = nil;
NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path
error:&error];
if(error == nil)
{
NSMutableArray* filesAndProperties = [NSMutableDictionary
dictionaryWithCapacity:[files count]];
for(NSString* path in files)
{
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:NSFileModificationDate
error:&error];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];
if(error == nil)
{
[filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
path, @"path",
modDate, @"lastModDate",
nil]];
}
}
NSArray* sortedFiles = [files sortedArrayUsingFunction:&lastModifiedSort
context:nil];
// SUCCESS!!
NSLog(@"sortedFiles: %@", sortedFiles);
}
else
{
NSLog(@"Encountered error while accessing contents of %@: %@", path, error);
}
}