如何在每个模拟器运行时替换我的应用程序中的数据库(使用我正在处理的数据库)? (仍在添加数据并想检查它是否看起来不错)
我尝试了这个,但它似乎不起作用,仍然使用旧数据库:
- (void)viewDidLoad
{
dbname = @"animaldatabase.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
dbpath = [documentsDir stringByAppendingPathComponent:dbname];
[self checkAndCreateDatabase];
[self readAnimalsFromDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view.
mylabel.text = [NSString stringWithFormat:@"%d", [animals count]];
}
- (void) checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:dbpath];
if (success) {
//return;
[fileManager removeItemAtPath:dbpath error:nil];
}
NSString *dbPathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbname];
[fileManager copyItemAtPath:dbPathFromApp toPath:dbpath error:nil];
}
iPhone 数据库的位置在哪里?当我的应用程序将数据库复制到 iPhone 时,它最终会去哪里?
更新
还添加了加载代码。
森蒂尔库玛:
我不明白这应该如何解决问题?如果复制或我的数据库已经存在,这不是会跳过它吗?
我想要的是删除我的 iPhone 应用程序中的数据库。导入新数据库然后运行它。
最佳答案
使用以下代码代替它。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
databaseName=@"yourfileName.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
}
-(void) checkAndCreateDatabase {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
else
printf("NO File found");
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
关于iPhone ios 5,在每个模拟器运行时重新创建数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11358998/