iPhone应用数据库

时间:2011-02-14 16:36:34

标签: iphone sqlite

所以我可以访问iPhone / iPod应用程序(Objective-C)中的只读SQLite数据库,但我正在编写一个具有可写数据库的新应用程序。显然,r / w文件必须位于用户可写目录中。我的问题是,我应该将一个空数据库与应用程序一起发送并将其复制到r / w位置,还是在应用程序第一次启动时动态创建r / w数据库?

1 个答案:

答案 0 :(得分:1)

你可以做任何一件事,但是你创建一个空数据库,把它放在你的包中然后在你的AppDelegate.m文件中这样做会容易得多(并且不易出错):

- (void)prepareDatabase
{
    //add Database Versioning check to see if the resources database is newer
    // generally as simple as naming your database with a version on the end

    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/YOURDATABASE.s3db"];
    if(![filemanager fileExistsAtPath:databasePath]) {
        //Database doesn't exist yet, so we copy it from our resources
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/YOURDATABASE.s3db"];
        if([filemanager copyItemAtPath:defaultDBPath toPath:databasePath error:nil]) {
            NSLog(@"Database Copied from resources");           
        } else {
            NSLog(@"Database copy FAILED from %@ to %@",defaultDBPath,databasePath);
        }
    }
}

然后在您的applicationDidFinishLaunching:方法中调用:

[self prepareDatabase];