Obtenez le contenu du répertoire dans l'ordre modifié date
-
19-09-2019 - |
Question
Y at-il une méthode pour obtenir le contenu d'un dossier dans un ordre particulier? Je voudrais un tableau de fichier attribut dictionnaires (ou un fichier que les noms) commandés par date de modification.
En ce moment, je suis en train de faire de cette façon:
- obtenir un tableau avec les noms de fichier
- obtenir les attributs de chaque fichier
- stocker le chemin du fichier et date de modification dans un dictionnaire avec la date comme une clé
Ensuite, je dois sortir le dictionnaire pour la date, mais je me demandais s'il y a un moyen plus facile? Sinon, est-il un extrait de code quelque part qui le fera pour moi?
Merci.
La solution
Code de Nall m'a fait ci-dessus dans la bonne direction, mais je pense qu'il ya des erreurs dans le code comme affiché ci-dessus. Par exemple:
-
Pourquoi est-
filesAndProperties
allouée à l'aideNMutableDictonary
plutôt que d'unNSMutableArray
? -
Le code ci-dessus passe le mauvais paramètre pourNSDictionary* properties = [[NSFileManager defaultManager] attributesOfItemAtPath:NSFileModificationDate error:&error];
attributesOfItemAtPath
- il devrait êtreattributesOfItemAtPath:path
-
Votre triez le tableau de
files
, mais vous devriez être le trifilesAndProperties
.
Je l'ai mis en œuvre le même, avec des corrections, et en utilisant des blocs et affichés ci-dessous:
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsPath = [searchPaths objectAtIndex: 0];
NSError* error = nil;
NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
if(error != nil) {
NSLog(@"Error in reading files: %@", [error localizedDescription]);
return;
}
// sort by creation date
NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
for(NSString* file in filesArray) {
NSString* filePath = [iMgr.documentsPath stringByAppendingPathComponent:file];
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:filePath
error:&error];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];
if(error == nil)
{
[filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
file, @"path",
modDate, @"lastModDate",
nil]];
}
}
// sort using a block
// order inverted as we want latest date first
NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
^(id path1, id path2)
{
// compare
NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:
[path2 objectForKey:@"lastModDate"]];
// invert ordering
if (comp == NSOrderedDescending) {
comp = NSOrderedAscending;
}
else if(comp == NSOrderedAscending){
comp = NSOrderedDescending;
}
return comp;
}];
Autres conseils
Que diriez-vous ceci:
// Application documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:documentsURL
includingPropertiesForKeys:@[NSURLContentModificationDateKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSArray *sortedContent = [directoryContent sortedArrayUsingComparator:
^(NSURL *file1, NSURL *file2)
{
// compare
NSDate *file1Date;
[file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];
NSDate *file2Date;
[file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];
// Ascending:
return [file1Date compare: file2Date];
// Descending:
//return [file2Date compare: file1Date];
}];
... Simpler
NSArray* filelist_sorted;
filelist_sorted = [filelist_raw sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary* first_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj1] error:nil];
NSDate* first = [first_properties objectForKey:NSFileModificationDate];
NSDictionary* second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj2] error:nil];
NSDate* second = [second_properties objectForKey:NSFileModificationDate];
return [second compare:first];
}];
Il est trop lent
[[NSFileManager defaultManager]
attributesOfItemAtPath:NSFileModificationDate
error:&error];
Essayez ce code:
+ (NSDate*) getModificationDateForFileAtPath:(NSString*)path {
struct tm* date; // create a time structure
struct stat attrib; // create a file attribute structure
stat([path UTF8String], &attrib); // get the attributes of afile.txt
date = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setSecond: date->tm_sec];
[comps setMinute: date->tm_min];
[comps setHour: date->tm_hour];
[comps setDay: date->tm_mday];
[comps setMonth: date->tm_mon + 1];
[comps setYear: date->tm_year + 1900];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *modificationDate = [[cal dateFromComponents:comps] addTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT]];
[comps release];
return modificationDate;
}
Le code ne fonctionne pas dans l'iPhone SDK, plein d'erreur de compilation. S'il vous plaît trouver le code mis à jour `
NSInteger lastModifiedSort(id path1, id path2, void* context)
{
int comp = [[path1 objectForKey:@"lastModDate"] compare:
[path2 objectForKey:@"lastModDate"]];
return comp;
}
-(NSArray *)filesByModDate:(NSString*) path{
NSError* error = nil;
NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path
error:&error];
if(error == nil)
{
NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
for(NSString* imgName in filesArray)
{
NSString *imgPath = [NSString stringWithFormat:@"%@/%@",path,imgName];
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:imgPath
error:&error];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];
if(error == nil)
{
[filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
imgName, @"path",
modDate, @"lastModDate",
nil]];
}else{
NSLog(@"%@",[error description]);
}
}
NSArray* sortedFiles = [filesAndProperties sortedArrayUsingFunction:&lastModifiedSort context:nil];
NSLog(@"sortedFiles: %@", sortedFiles);
return sortedFiles;
}
else
{
NSLog(@"Encountered error while accessing contents of %@: %@", path, error);
}
return filesArray;
}
`