【问题标题】:How to sort files by modified date in iOS如何在iOS中按修改日期对文件进行排序
【发布时间】:2011-09-15 05:46:05
【问题描述】:

我使用 NSFileManager 检索文件夹中的文件,我想按修改日期对它们进行排序。该怎么做?

谢谢。

【问题讨论】:

    标签: iphone ios ipad


    【解决方案1】:

    到目前为止,您尝试了什么?

    我还没有这样做,但快速浏览一下文档让我认为您应该尝试以下操作:

    1. 调用-contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: 并指定NSURLContentModificationDateKey 作为键之一。
    2. 您将返回一个 NSURL 对象数组,然后您可以使用像 -sortedArrayUsingComparator: 这样的 NSArray 方法对其进行排序。
    3. 传入一个比较器块,该块使用-getResourceValue:forKey:error: 查找每个 NSURL 的修改日期。

    更新:当我写上面的答案时,-getResourceValue:forKey:error: 存在于 iOS 中,但没有做任何事情。该方法现在从 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);
    

    【讨论】:

    • 奇怪的是,getResourceValue:forKey:error 的文档说“这个方法在 iOS 中没有实现,所以它不执行任何操作。”在其下方,他们说“在 iOS 4.0 及更高版本中可用”。为什么他们会添加一个未实现的方法是令人困惑的。 ?=|更多:themusingsofalostprogrammer.com/2011/06/…
    • Foundation 框架对 MacOS X 和 iOS 来说是通用的,所以它可能只是因为它在 MacOS X 中有用。另一方面,它可能仍然值得尝试,希望文档是不正确 - 它确实偶尔会发生。
    • @Dustin,请注意,文档现在表明 getResourceValue:forKey:error: 在 iOS 5 中可以使用。我进行了快速测试并确认它可以正常工作。我也会更新上面的答案。
    • 酷。我们是否知道它是否在内部进行了优化以仅从文件中获取这些值?我感觉 NSFileManager 中没有任何东西被优化——我最近甚至学会了 fileExists: 加载文件的每个属性。
    • 事实证明,读取所有元数据与检查 iOS 上是否存在文件一样快,这解释了 fileExists。它用所有信息填充 NSDictionary 有点烦人。我想如果你想减少开销,你需要使用 stat。
    【解决方案2】:
    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);
    

    【讨论】:

      【解决方案3】:
      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;
      }
      

      现在,稍后在您的代码中。

      NSMutableArray *mary = [NSMutableArray arrayWithArray:filePathsArray];
      
      [mary sortUsingFunction:contentsOfDirSort context:nil];
      
      // Use mary...
      

      【讨论】:

        【解决方案4】:

        快速方法:

        -(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;
            }
        }
        

        【讨论】:

          【解决方案5】:

          在超过NSFileManager的类别中:

          static  NSInteger contentsOfDirSort(NSURL *leftURL, NSURL *rightURL, void *ptr)
          {
              (void)ptr;
              
              NSDate * dateLeft ;
              [leftURL getResourceValue:&dateLeft
                                 forKey:NSURLContentModificationDateKey
                                  error:nil] ;
              
              NSDate * dateRight ;
              [rightURL 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] ;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-12-25
            • 1970-01-01
            • 2021-09-07
            • 2010-09-26
            • 2021-11-02
            • 1970-01-01
            相关资源
            最近更新 更多