当用户首次使用我的应用程序时,它应该将包中的配置文件复制到某个文件夹中。然后用户可以摆弄这个文件,如果他们搞砸了,他们只需按下“恢复”,这将删除文件并从包中再次复制。
- (void) resetPresets
{
LOG_( @"Copying tunings file from original..." );
// copy default tunings -> curr tunings file
NSString* appSupportDir = [NSFileManager appSupportDir];
NSString* tuningsPath = [appSupportDir stringByAppendingPathComponent: @"tunings.txt"];
NSBundle* bundle = [NSBundle mainBundle];
NSString* origTuningsPath = [bundle pathForResource: @"tuningsOriginal"
ofType: @"txt" ];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError* error = nil;
if( [fileManager fileExistsAtPath: tuningsPath] )
{
[fileManager removeItemAtPath: tuningsPath
error: & error ];
if( error )
LOG( @"\n ERROR: %@ \n %@ \n", [error userInfo], [error localizedFailureReason] );
}
assert( [fileManager fileExistsAtPath: origTuningsPath] );
[fileManager copyItemAtPath: origTuningsPath
toPath: tuningsPath
error: & error ];
if( error )
LOG( @"\n ERROR: %@ \n %@ \n", [error userInfo], [error localizedFailureReason] );
LOG( @"done!" );
// load profiles from it
[self loadProfilesFromFile: tuningsPath ];
// auto-sets active preset index to 0 & saves prefs
self.activeThemeIndex = 0;
}
依赖于一个简单的类别:
#import "NSFileManager+addons.h"
@implementation NSFileManager ( NSFileManager_addons )
+ (NSString *) appSupportDir
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(
NSApplicationSupportDirectory,
NSUserDomainMask,
YES
);
NSString* appSupportDir = [paths objectAtIndex: 0];
return appSupportDir;
}
@end
这是引起问题的一行:
[fileManager copyItemAtPath: origTuningsPath
toPath: tuningsPath
error: & error ];
这是控制台输出:
[预设init]预设 - >第一次运行!设置为默认值 预设从原始文件中复制调整文件...错误:{ NSDestinationFilePath = “在/ var /移动/应用/ 38FC3C65-74AF-4892-B48D-A3508A8CF404 /库/应用程序 支持/ tunings.txt“; NSFilePath = “/var/mobile/Applications/38FC3C65-74AF-4892-B48D-A3508A8CF404/Fork.app/tuningsOriginal.txt”; NSUserStringVariant =复制;没有这样的文件或目录
为什么抱怨没有这样的文件或目录?显然不应该存在这样的文件。当您将文件复制到新位置时,您不希望文件存在。
所以我猜它正在抱怨这个目录。但是我使用一种相当标准的方法将目录删除了。到底是怎么回事?这不是正确使用的目录吗?或者我做错了什么?
答案 0 :(得分:3)
NSSearchPathForDirectoriesInDomains
返回的目录不保证存在;如有必要,您需要自己创建它们(请参阅the documentation)。 NSFileManager的createDirectoryAtPath:withIntermediateDirectories:attributes:error:
可以帮助解决这个问题。