当用户第一次使用我的应用程序时,它应该将包中的配置文件复制到某个文件夹中。然后用户可以摆弄这个文件,如果他们把它弄乱了,他们可以简单地按“恢复”,这将删除该文件并从包中再次复制它。
- (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 ];
这是控制台输出:
[presets init] Presets -> first run! Setting up with default presets Copying tunings file from original... ERROR: { NSDestinationFilePath = "/var/mobile/Applications/38FC3C65-74AF-4892-B48D-A3508A8CF404/Library/Application Support/tunings.txt"; NSFilePath = "/var/mobile/Applications/38FC3C65-74AF-4892-B48D-A3508A8CF404/Fork.app/tuningsOriginal.txt"; NSUserStringVariant = Copy; } No such file or directory
为什么提示没有这样的文件或目录?显然不应该存在这样的文件。当您将文件复制到新位置时,您不希望文件在那里。
所以我猜它在提示目录。但是我已经使用一种相当标准的方法将目录捞出。到底是怎么回事?这不是要使用的正确目录吗?还是我做错了什么?
最佳答案
NSSearchPathForDirectoriesInDomains
返回的目录不保证存在;如有必要,您需要自己创建它们(参见 the documentation)。 NSFileManager 的 createDirectoryAtPath:withIntermediateDirectories:attributes:error:
可以帮忙。
关于iOS:在应用程序启动时从包中复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6776186/