codice di Nall sopra mi ha segnalato nella giusta direzione, ma Penso che ci siano alcuni errori nel codice come pubblicato sopra. Per esempio:
- Perché
filesAndProperties
assegnati utilizzando NMutableDictonary
piuttosto che un NSMutableArray
?
-
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:NSFileModificationDate
error:&error];
Il codice di cui sopra sta passando il parametro sbagliato per attributesOfItemAtPath
- Va attributesOfItemAtPath:path
- Voi Ordinamento della matrice
files
, ma si dovrebbe essere di ordinamento filesAndProperties
.
ho implementato lo stesso, con le correzioni, e l'utilizzo di blocchi e postato qui sotto:
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;
}];
fonte
2010-07-29 01:54:05
Per invertire l'ordine è possibile moltiplicare il risultato del confronto per -1. –
Per invertire l'ordine è sufficiente utilizzare 'return [[path2 objectForKey: @" lastModDate "] compare: [percorso1 oggettoPerfetto: @" ultimoModDato "]];' – Ievgen