【问题标题】:iOS: Archive Path containing a dateiOS:包含日期的存档路径
【发布时间】:2014-11-18 15:39:30
【问题描述】:

我需要我的存档路径文件名来包含日期。

但是,既然我已经完成了这项工作......我意识到我无法获得我的存档路径,因为我不知道应用程序打开的日期。

无论如何要查找存档路径作为通配符含义:

item.archive.%@ 其中 %@ 可以是任何东西(例如日期)?

我正在使用 NSKeyedArchiver。我的文件保存了——我的问题是在重新打开应用程序后获取文件,因为我不知道日期是什么。

更新:

在我的 itemArchivePath 函数中:

NSString *filename = [[NSString alloc] initWithFormat:@"items.archive.%@", date];

return [documentDirectory stringByAppendingPathComponent:filename];

由于我在文件名中附加了一个日期,如果我调用 itemArchivePath - 它不会有日期,因为它不知道日期是什么。无论如何我可以使用通配符获取项目路径 - 只会保存 1 个文件,我知道路径的开头将是 items.archive。

【问题讨论】:

  • 如果我们能看到一些代码来显示您保存对象的位置以及保存方式,那就更清楚了。
  • @GuyKogus 查看更新。谢谢。
  • dateNSString 还是 NSDate
  • @rmaddy 这是一个 NSString
  • @SandyD。很好,因为您不能依赖 NSDate 的格式。

标签: ios objective-c nskeyedarchiver


【解决方案1】:

此代码将允许您获取存档文件的所有 URL:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentDirectory = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
NSError *error;
NSArray *contents = [fileManager contentsOfDirectoryAtURL:documentDirectory
                               includingPropertiesForKeys:nil
                                                  options:NSDirectoryEnumerationSkipsSubdirectoryDescendants | NSDirectoryEnumerationSkipsPackageDescendants | NSDirectoryEnumerationSkipsHiddenFiles
                                                    error:&error];
if (contents)
{
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return [[(NSURL *)evaluatedObject lastPathComponent] hasPrefix:@"items.archive."];
    }];
    contents = [contents filteredArrayUsingPredicate:predicate];
    NSLog(@"Archive items: %@", contents);
}
else
{
    NSLog(@"Failed to get contents:\n%@", error);
}

您可以通过确保(在谓词中)在这些 URL 中有文件(而不是文件夹)来使其更加健壮,但我猜这对于您的情况来说可能是矫枉过正。

【讨论】:

  • 谢谢!感谢您的帮助!
【解决方案2】:

使用NSFileManager 获取存档文件夹中所有文件的路径。根据您归档的方式,您将拥有一个可以使用的文件名或一个可以向用户显示的文件列表(日期)。

【讨论】:

  • 好的,我会调查的。感谢您的评论。感谢您的帮助。
猜你喜欢
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2010-11-20
  • 2012-06-11
  • 2012-03-09
  • 2011-02-15
相关资源
最近更新 更多