【发布时间】: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