use*_*332 6 directory file objective-c ios
我试图获取i目录中的所有文件,并根据创建日期或修改日期对它们进行排序.有很多例子,但我不能让他们中的任何一个工作.
任何人都有一个很好的例子如何从按日期排序的目录中获取文件数组?
这里有两个步骤,获取具有创建日期的文件列表,并对它们进行排序.
为了便于以后对它们进行排序,我创建了一个对象来保存带有修改日期的路径:
@interface PathWithModDate : NSObject
@property (strong) NSString *path;
@property (strong) NSDate *modDate;
@end
@implementation PathWithModDate
@end
Run Code Online (Sandbox Code Playgroud)
现在,要获取文件和文件夹列表(不是深度搜索),请使用以下命令:
- (NSArray*)getFilesAtPathSortedByModificationDate:(NSString*)folderPath {
NSArray *allPaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:folderPath error:nil];
NSMutableArray *sortedPaths = [NSMutableArray new];
for (NSString *path in allPaths) {
NSString *fullPath = [folderPath stringByAppendingPathComponent:path];
NSDictionary *attr = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:nil];
NSDate *modDate = [attr objectForKey:NSFileModificationDate];
PathWithModDate *pathWithDate = [[PathWithModDate alloc] init];
pathWithDate.path = fullPath;
pathWithDate.modDate = modDate;
[sortedPaths addObject:pathWithDate];
}
[sortedPaths sortUsingComparator:^(PathWithModDate *path1, PathWithModDate *path2) {
// Descending (most recently modified first)
return [path2.modDate compare:path1.modDate];
}];
return sortedPaths;
}
Run Code Online (Sandbox Code Playgroud)
请注意,一旦我创建了一个PathWithDate对象数组,我sortUsingComparator就会按正确的顺序放置它们(我选择了降序).为了使用创建日期,请改为使用[attr objectForKey:NSFileCreationDate].
| 归档时间: |
|
| 查看次数: |
4598 次 |
| 最近记录: |