2009-10-06 27 views
33

特定の順序でフォルダの内容を取得する方法はありますか?私は、ファイル属性辞書(または単にファイル名)の配列を変更した日付順に並べ替えたい。ディレクトリの内容を変更した日付で取得する

は今のところ、私はそれをこのようにやっている:

  • ファイル名
  • を持つ配列は、辞書内の各ファイルの属性
  • ストアファイルのパスと変更日付をゲット日付をキーとして使用

次は、日付順に辞書を出力する必要がありますが、簡単な方法があるかどうか疑問に思っていますか?そうでない場合、私のためにこれを行うコードスニペットがどこかにありますか?

ありがとうございました。

答えて

35

ナルのコードは、上記右方向に私を指摘したが、私は上に掲示されたコードにいくつかの間違いがあると思います。例えば:

  1. はなぜfilesAndPropertiesNMutableDictonaryではなくNSMutableArrayを使用して割り当てられていますか?

  2. 
    NSDictionary* properties = [[NSFileManager defaultManager] 
                 attributesOfItemAtPath:NSFileModificationDate 
                 error:&error]; 
    
    
    上記のコードはattributesOfItemAtPathために間違ったパラメータを渡している - それは、attributesOfItemAtPath:path

  3. する必要がありますあなたはfiles配列をソートされますが、filesAndPropertiesをソートする必要があります。


私は修正して、同じことを実現して、ブロックを使用し、下に掲載している。これについて


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

+0

順序を逆にするには、単に比較結果に-1を掛けることができます。 –

+5

順序を逆順にするには 'return [[path2 objectForKey:@" lastModDate "]を比較してください:[path1 objectForKey:@" lastModDate "]]; ' – Ievgen

0

iPhone SDKではコードが正しく動作しません。コンパイルエラーです。それは

[[NSFileManager defaultManager] 
           attributesOfItemAtPath:NSFileModificationDate 
           error:&error]; 

このコードを試してみてくださいあまりにも遅いです更新されたコード `

NSInteger lastModifiedSort(id path1, id path2, void* context) 
{ 
    int comp = [[path1 objectForKey:@"lastModDate"] compare: 
    [path2 objectForKey:@"lastModDate"]]; 
    return comp; 
} 

-(NSArray *)filesByModDate:(NSString*) path{ 

    NSError* error = nil; 

    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path 
                     error:&error]; 
    if(error == nil) 
    { 
     NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]]; 

     for(NSString* imgName in filesArray) 
     { 

      NSString *imgPath = [NSString stringWithFormat:@"%@/%@",path,imgName]; 
      NSDictionary* properties = [[NSFileManager defaultManager] 
             attributesOfItemAtPath:imgPath 
             error:&error]; 

      NSDate* modDate = [properties objectForKey:NSFileModificationDate]; 

      if(error == nil) 
      { 
       [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys: 
               imgName, @"path", 
               modDate, @"lastModDate", 
               nil]];      
      }else{ 
       NSLog(@"%@",[error description]); 
      } 
     } 
     NSArray* sortedFiles = [filesAndProperties sortedArrayUsingFunction:&lastModifiedSort context:nil]; 

     NSLog(@"sortedFiles: %@", sortedFiles);  
     return sortedFiles; 
    } 
    else 
    { 
     NSLog(@"Encountered error while accessing contents of %@: %@", path, error); 
    } 

    return filesArray; 
} 

`

+0

お返事ありがとうございます。ここでiPhone SDK(NSURLContentModificationDateKeyと他のいくつかのNSURLメソッド)では動作しないものがいくつかあります。 –

+0

iPhone SDKで動作するように変更しようとしましたが、getResourceValueは存在しません。私はiPhoneの配列の並べ替えを探します。 –

+0

nevan、これをiPhone SDKの制約内で動作するようにアップデートしました – nall

5

を見つけてください:

+ (NSDate*) getModificationDateForFileAtPath:(NSString*)path { 
    struct tm* date; // create a time structure 
    struct stat attrib; // create a file attribute structure 

    stat([path UTF8String], &attrib); // get the attributes of afile.txt 

    date = gmtime(&(attrib.st_mtime)); // Get the last modified time and put it into the time structure 

    NSDateComponents *comps = [[NSDateComponents alloc] init]; 
    [comps setSecond: date->tm_sec]; 
    [comps setMinute: date->tm_min]; 
    [comps setHour:  date->tm_hour]; 
    [comps setDay:  date->tm_mday]; 
    [comps setMonth: date->tm_mon + 1]; 
    [comps setYear:  date->tm_year + 1900]; 

    NSCalendar *cal = [NSCalendar currentCalendar]; 
    NSDate *modificationDate = [[cal dateFromComponents:comps] addTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT]]; 

    [comps release]; 

    return modificationDate; 
} 
+0

これははるかに高速です。私のテストでは4倍速くなりました。私はこれで1つのバグに遭遇しました。私のgmtimeはGMTではなくUTCを返しています。時には問題を引き起こした1時間の違いがありました。 –

+0

コードを次のように調整します。 NSCalendar * cal = [NSCalendar currentCalendar]; NSTimeZone * tz = [NSTimeZone timeZoneWithAbbreviation:[[NSString alloc] initWithUTF8String:date-> tm_zone]]; cal.timeZone = tz; –

+0

#import "sys/stat.h" –

10
シンプル

...

NSArray* filelist_sorted; 
filelist_sorted = [filelist_raw sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
    NSDictionary* first_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj1] error:nil]; 
    NSDate*  first    = [first_properties objectForKey:NSFileModificationDate]; 
    NSDictionary* second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj2] error:nil]; 
    NSDate*  second   = [second_properties objectForKey:NSFileModificationDate]; 
    return [second compare:first]; 
}]; 
+0

path_thumbとは何ですか? – DJTano

19

方法:

// Application documents directory 
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:documentsURL 
                  includingPropertiesForKeys:@[NSURLContentModificationDateKey] 
                      options:NSDirectoryEnumerationSkipsHiddenFiles 
                       error:nil]; 

NSArray *sortedContent = [directoryContent sortedArrayUsingComparator: 
         ^(NSURL *file1, NSURL *file2) 
         { 
          // compare 
          NSDate *file1Date; 
          [file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil]; 

          NSDate *file2Date; 
          [file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil]; 

          // Ascending: 
          return [file1Date compare: file2Date]; 
          // Descending: 
          //return [file2Date compare: file1Date]; 
         }]; 
+11

私はこのソリューションを探していて、上記のコードを使用してしまいました。だから私は他の人よりもきれいだと思うのでここに入れている;) –

関連する問題