iPhone ios 5,在每个模拟器运行时重新创建数据库?

标签 iphone cocoa sqlite

如何在每个模拟器运行时替换我的应用程序中的数据库(使用我正在处理的数据库)? (仍在添加数据并想检查它是否看起来不错)

我尝试了这个,但它似乎不起作用,仍然使用旧数据库:

- (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/

相关文章:

iphone - Objective-C @Selector(methodWithArguments)

iphone - 无法从第三方链接安装 iOS 版本并仅显示白色图标

iphone - ios获取相机输入

objective-c - 向 Cocoa 应用程序添加帮助

xcode - cocoa 应用程序中的 OpenCV Blob 跟踪

sqlite - 得到的行范围平均使用偏移和限制?

node.js - 错误 : no such function: json_each in SQLite with JSON1 installed

iphone - UITableView中的静态图片

swift - 简单的 NSPageController 示例抛出未知 subview 警告并停止工作

c# - Sqlite 中的多线程