Erhalten Sie Verzeichnisinhalt Datum geändert, um
-
19-09-2019 - |
Frage
Gibt es eine Methode, den Inhalt eines Ordners in einer bestimmten Reihenfolge zu bekommen? Ich möchte eine Reihe von Dateiattribut Wörterbücher (oder nur Dateinamen) nach Datum geordnet geändert.
Im Moment bin ich es auf diese Weise tun:
- erhalten ein Array mit den Dateinamen
- erhalten die Attribute jeder Datei
- Speicher der Pfad der Datei und Änderungsdatum in einem Wörterbuch mit dem Datum als Schlüssel
Als nächstes habe ich das Wörterbuch in chronologischer Reihenfolge zur Ausgabe, aber ich fragte mich, ob es ein einfacher Weg ist? Wenn nicht, gibt es einen Code-Schnipsel irgendwo, die das für mich tun?
Danke.
Lösung
nall Code oben weist mich in der richtigen Richtung, aber ich denke, es gibt einige Fehler im Code, wie oben geschrieben. Zum Beispiel:
-
Warum zugeordnet
filesAndProperties
NMutableDictonary
mit eher als einNSMutableArray
? -
Der obige Code passiert den falschen Parameter fürNSDictionary* properties = [[NSFileManager defaultManager] attributesOfItemAtPath:NSFileModificationDate error:&error];
attributesOfItemAtPath
- esattributesOfItemAtPath:path
sein sollte -
Sie Sortieren der
files
Array, aber Sie sollten SortierungfilesAndProperties
werden.
Ich habe das gleiche umgesetzt, mit Korrekturen und Verwendung von Blöcken und veröffentlichte unter:
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;
}];
Andere Tipps
Wie wäre es damit:
// 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];
}];
Einfachere ...
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];
}];
Es ist zu langsam
[[NSFileManager defaultManager]
attributesOfItemAtPath:NSFileModificationDate
error:&error];
Versuchen Sie diesen Code ein:
+ (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;
}
-Code funktioniert nicht in iPhone SDK, voller Übersetzungsfehler. Bitte finden aktualisierten Code `
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;
}
`