【问题标题】:NSFileManager instances changing other instance's currentDirectoryPathNSFileManager 实例更改其他实例的 currentDirectoryPath
【发布时间】:2014-11-06 03:30:00
【问题描述】:

我在 iOS 应用程序中继承 NSFileManager 以添加一些额外的行为。这样做时,我遇到了一个无需子类化就可以演示的问题。

总而言之,我创建了一个 NSFileManager 的实例,更改它的 currentDirectoryPath,打印它,然后创建另一个实例,将它的 currentDirectoryPath 设置为别的东西,我最终在两个实例上都得到了相同的 currentDirectoryPath。

这是复制这种行为的方法:

NSString * pathA = [NSHomeDirectory() stringByAppendingPathComponent:@"directoryA"];
NSString * pathB = [NSHomeDirectory() stringByAppendingPathComponent:@"directoryB"];

[[NSFileManager defaultManager] createDirectoryAtPath:pathA withIntermediateDirectories:NO attributes:nil error:nil];
[[NSFileManager defaultManager] createDirectoryAtPath:pathB withIntermediateDirectories:NO attributes:nil error:nil];


NSFileManager * fileManagerA = [[CCFileManager alloc] init];
[fileManagerA changeCurrentDirectoryPath:pathA];

NSLog( @"fileManagerA.currentDirectoryPath = %@", fileManagerA.currentDirectoryPath );  // outputs pathA, as expected


NSFileManager * fileManagerB = [[CCFileManager alloc] init];
[fileManagerB changeCurrentDirectoryPath:pathB];

NSLog( @"fileManagerB.currentDirectoryPath = %@", fileManagerB.currentDirectoryPath );  // outputs pathB, as expected
NSLog( @"fileManagerA.currentDirectoryPath = %@", fileManagerA.currentDirectoryPath );  // outputs pathB, why?

我在 iOS 7 和 8 上尝试了 SDK 7.1 和 8.1,结果相同。

【问题讨论】:

  • [NSFileManager defaultManager] 是一个单例。
  • @danh 不是 defaultManager 单身人士吗?
  • @danh 我认为问题在于 changeCurrentDirectoryPath 更改了整个过程的设置,而不仅仅是那个实例。
  • 对不起,我应该更仔细地阅读。您能否通过比较指针来证明您有两个不同的实例:fileManagerA== fileManagerB 或 NSLog(@"%p vs %p", fileManagerA, fileManagerB);
  • @danh,是的,它们是不同的。 “0x7964ad80 vs 0x79673dd0” - 我想我已经找到了原因。我猜 currentDirectoryPath 更像是一个进程范围的设置,而不是一个实例属性。

标签: ios objective-c nsfilemanager


【解决方案1】:

我在documentation for NSFileManager找到了答案。

所有相对路径名都隐含地引用当前工作 目录。更改当前工作目录仅影响路径 在当前进程中创建。

CurrentDirectoryPath 会针对整个过程进行更改,而不仅仅是 NSFileManager 的那个实例

【讨论】:

  • 这与 man 2 chdir 和 POSIX 行为一致。整个过程的路径都改变了(包括对 open() 的调用,...)
  • @Antzi 确实如此。我错误地认为这是 NSFileManager 将用作其路径“基础”的属性,但它更像是当前工作目录的网关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2012-08-24
  • 2020-10-12
  • 2010-12-11
  • 2020-03-28
相关资源
最近更新 更多