【发布时间】:2015-03-30 08:54:26
【问题描述】:
问题:长时间运行没有问题后,我的数据库让我头疼,它只是不会停留在 NSDocumentDirectory 中的位置。数据库奇怪地消失了。
我从不清除文档文件夹或删除任何内容。它只包含数据库并在其中保存一些图像,如果用户想要保留它们,它们会被下载。
有人知道会发生什么吗?
在解决这个问题 3 天后,我无法想出一个可能的解决方案,所以请帮助我! :(
在我的数据库单例中,我有以下初始化方法
- (id)initWithName{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:kDatabaseName];
//kDatabaseName = nameOfDatabase.db
[self checkAndCreateDatabase];
return self;
}
还有 checkAndCreateDatabase - 方法:
- (void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
NSURL *urlpath = [NSURL fileURLWithPath:databasePath];
NSError *error = nil;
[urlpath setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(success && sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(@"database opened");
sqlite3_close(database);
return;
}
else{
sqlite3_close(database);
NSLog(@"Database was created");
}
// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
//NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:databaseName ofType:@"sqlite3"];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
if ([self createTables]){ //creates tables of DB, works fine
NSLog(@"Tables were created");
} else {
NSLog(@"Database failed to create and open");
}
}
此代码连续工作了一年。突然,当我需要进行一些更新时,数据库不再保存。 经过大量故障排除后,我发现数据库正在 Documents 文件夹中创建,但是当我尝试访问完全相同的路径时(因为我没有触摸变量),它消失了,它是表格。
我尝试了不同版本的存储库,它们似乎都有问题。我真的要生气了。 :(
【问题讨论】:
标签: objective-c sqlite nsdocumentdirectory