以修改日期的顺序获取目录内容 [英] Get directory contents in date modified order
问题描述
是否有按特定顺序获取文件夹内容的方法?我想要按修改日期排序的文件属性字典(或只是文件名)的数组.
Is there an method to get the contents of a folder in a particular order? I'd like an array of file attribute dictionaries (or just file names) ordered by date modified.
现在,我这样做是这样的:
Right now, I'm doing it this way:
- 获取具有文件名的数组
- 获取每个文件的属性
- 将文件的路径和修改的日期存储在以日期为键的字典中
接下来,我必须按日期顺序输出字典,但是我想知道是否有更简单的方法?如果没有,那么某个地方是否有代码片段可以为我做到这一点?
Next I have to output the dictionary in date order, but I wondered if there's an easier way? If not, is there a code snippet somewhere which will do this for me?
谢谢.
推荐答案
上面的nall代码为我指明了正确的方向,但是我认为上面发布的代码中存在一些错误.例如:
nall's code above pointed me in the right direction, but I think there are some mistakes in the code as posted above. For instance:
-
为什么使用
NMutableDictonary
而不是NSMutableArray
分配filesAndProperties
?
-
Why is
filesAndProperties
allocated usingNMutableDictonary
rather than anNSMutableArray
?
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:NSFileModificationDate
error:&error];
上面的代码为attributesOfItemAtPath
传递了错误的参数-应该为attributesOfItemAtPath:path
files
数组进行排序,但是您应该正在对filesAndProperties
进行排序.
The code above is passing the wrong parameter for attributesOfItemAtPath
- it should be attributesOfItemAtPath:path
files
array, but you should be sorting filesAndProperties
.
我已经实现了相同的功能,并进行了更正,并使用了块,并在下面发布:
I have implemented the same, with corrections, and using blocks and posted below:
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;
}];
这篇关于以修改日期的顺序获取目录内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!