简体   繁体   English

如何在 iOS 中按修改日期对文件进行排序

[英]How to sort files by modified date in iOS

I used NSFileManager to retrieve the files in a folder, and I want to sort them by modified date.我使用 NSFileManager 检索文件夹中的文件,我想按修改日期对它们进行排序。 How to do that?怎么做?

Thanks.谢谢。

What have you tried so far?你试过什么了?

I haven't done this, but a quick look at the docs makes me think that you should try the following:我还没有这样做,但是快速浏览一下文档让我认为您应该尝试以下操作:

  1. Call -contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: and specify NSURLContentModificationDateKey as one of the keys.调用-contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:并指定NSURLContentModificationDateKey作为键之一。
  2. You'll get back an array of NSURL objects which you can then sort using an NSArray method like -sortedArrayUsingComparator: .您将返回一个 NSURL 对象数组,然后您可以使用 NSArray 方法(如-sortedArrayUsingComparator: )对其进行排序。
  3. Pass in a comparator block that looks up the modification date for each NSURL using -getResourceValue:forKey:error: .传入一个比较器块,该块使用-getResourceValue:forKey:error:查找每个 NSURL 的修改日期。

Update: When I wrote the answer above, -getResourceValue:forKey:error: existed in iOS but didn't do anything.更新:当我写上面的答案时, -getResourceValue:forKey:error:存在于 iOS 但没有做任何事情。 That method is now functional as of iOS 5. The following code will log an app's resource files followed by a list of corresponding modification dates:该方法现在从 iOS 5 开始起作用。以下代码将记录应用程序的资源文件,后跟相应修改日期的列表:

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtURL:[[NSBundle mainBundle] resourceURL]
                        includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
                                           options:nil
                                             error:nil];
NSMutableArray *dates = [NSMutableArray array];
for (NSURL *f in files) {
    NSDate *d = nil;
    if ([f getResourceValue:&d forKey:NSURLContentModificationDateKey error:nil]) {
        [dates addObject:d];
    }
}
NSLog(@"Files: %@", files);
NSLog(@"Dates: %@", dates);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSMutableArray *originalImage = [[NSMutableArray alloc]init];

    for (int i = 1; i < [imageFilenames count]; i++)
    {
        NSString *imageName = [NSString stringWithFormat:@"%@/%@",documentsDirectory,[imageFilenames objectAtIndex:i] ];

    }

    //---------sorting image by date modified
    NSArray*  filelist_date_sorted;

    filelist_date_sorted = [imageFilenames sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
                            {
                                NSDictionary* first_properties  = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, obj1] error:nil];
                                NSDate *first = [first_properties  objectForKey:NSFileCreationDate];
                                NSDictionary *second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", documentsDirectory, obj2] error:nil];
                                NSDate *second = [second_properties objectForKey:NSFileCreationDate];
                                return [second compare:first];
                            }];

NSLog(@" Date sorted result is %@",filelist_date_sorted);
static static NSInteger contentsOfDirSort(NSString *left, NSString *right, void *ptr) {

    (void)ptr;

    struct stat finfo_l, r_finfo_r;

    if(-1 == stat([left UTF8String], &finfo_l))
        return NSOrderedSame;

    if(-1 == stat([right UTF8String], &finfo_r))
        return NSOrderedSame;

    if(finfo_l.st_mtime < finfo_r.st_mtime)
        return NSOrderedAscending;

    if(finfo_l.st_mtime > finfo_r.st_mtime)
        return NSOrderedDescending;

    return NSOrderedSame;
}

Now, later on in your code.现在,稍后在您的代码中。

NSMutableArray *mary = [NSMutableArray arrayWithArray:filePathsArray];

[mary sortUsingFunction:contentsOfDirSort context:nil];

// Use mary...

In a category over NSFileManager :NSFileManager的类别中:

static  NSInteger contentsOfDirSort(NSURL *leftURL, NSURL *rightURL, void *ptr)
{
    (void)ptr;

    NSDate * dateLeft ;
    [leftURL getResourceValue:&dateLeft
                       forKey:NSURLContentModificationDateKey
                        error:nil] ;

    NSDate * dateRight ;
    [leftURL getResourceValue:&dateRight
                       forKey:NSURLContentModificationDateKey
                        error:nil] ;

    return [dateLeft compare:dateRight];
}




- (NSArray *)contentsOrderedByDateOfDirectoryAtPath:(NSURL *)URLOfFolder ;
{
    NSArray *files = [self contentsOfDirectoryAtURL:URLOfFolder
                         includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
                                            options:0
                                              error:nil];

    return [files sortedArrayUsingFunction:contentsOfDirSort
                                   context:nil] ;
}

Quick Method:快速方法:

-(void)dateModified
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];

    //--- Listing file by name sort
    NSLog(@"\n File list %@",fileList);




    int num;
    //-- Listing file name with modified dated
    for (NSString *s in fileList)
    {
        NSString *filestring = [documentsDirectory stringByAppendingFormat:@"/%@",s];

        NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:filestring error:nil];
        NSString *modifiedDate = [filePathsArray1 objectForKey:NSFileModificationDate];
        NSLog(@"\n Modified Day : %@", modifiedDate);

        num=num+1;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM