【问题标题】:IOS - load local file in orderIOS - 按顺序加载本地文件
【发布时间】:2012-07-25 05:24:58
【问题描述】:

我在应用程序的 Document 文件夹中有一个图像列表。我想按创建日期的顺序加载图像。 我该怎么做?

【问题讨论】:

    标签: objective-c ios nsfilemanager


    【解决方案1】:

    我会看看:Getting a list of files in a directory with a glob

    特别是 NSFileManager。您可以查看文件的属性。从那里您很可能可以使用 NSPredicate 进行排序。

    【讨论】:

      【解决方案2】:

      此代码将按创建顺序枚举您的文档目录中的所有文件:

      查看代码中的 cmets 以了解发生了什么。

      NSFileManager *fm = [NSFileManager defaultManager];
      NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
      NSError *err;
      // Get all files with their creation date
      NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
          includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
          options:0
          error:&err];
      // Using file's URL as the key, store creation date as the value
      NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
      for (NSURL *f in files) {
          NSDate *creationDate;
          if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
              [urlWithDate setObject:creationDate forKey:f];
          }
      }
      // Sort the dictionary on the value, which is the creation key
      for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
          return [obj1 compare:obj2];
      }]) {
          // Check if the file is an image. Load if it is an image, otherwise skip.
          NSLog(@"%@", f);
      }
      

      【讨论】:

      • 很高兴看到如何在一个请求中加载所有文件及其属性
      猜你喜欢
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      相关资源
      最近更新 更多