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

时间:2012-07-06 08:55:23

标签: 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时,它最终会在哪里?

更新

还添加了加载代码。

Senthilkumar:

我看不出这应该如何解决这个问题?这不是只是跳过复制或我的数据库,如果它已经存在?

我想要的是删除我的iPhone应用程序中的数据库。导入新数据库,然后运行它。

2 个答案:

答案 0 :(得分:0)

使用以下代码代替。

- (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];

}

答案 1 :(得分:0)

为了帮助调试文件管理器操作,尝试使用error参数是有帮助的,如下所示:

NSError* error;
[fileManager copyItemAtPath:dbPathFromApp toPath:dbpath error: &error];
if (error != nil) {
    NSLog(@"copyItemAtPath generated error=%@", [error localizedDescription]);
}

如果这样做,错误消息将被写入调试器控制台/标准输出窗口。