我正在使用sqlite数据库,一切进展顺利。我在表中添加了4个条目,然后在我的xib文件中添加了textview。现在我希望这个数据应该从sqlite数据库中获取,该数据库放在项目的包中。但我没有得到如何从捆绑到目录路径调用此数据库。请帮我解决这个问题。
答案 0 :(得分:1)
使用此代码:
首先调用此方法,该方法将检查数据库文件是否存储在文档目录中。如果不是它会将您的文件写入文档目录。
-(void)openDatabase {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"databasefilename.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath
error:&error];
if (!success)
NSLog(@"Failed to create writable database file with message '%@'.",
[error localizedDescription]);
}
}
- (NSString *) getDBPath {
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"databasefilename.sqlite"];
}
然后检查Appdelegate或您想要的任何其他课程:
if (sqlite3_open([[self getDBPath] UTF8String], &YOUR_SQLITE3_OBJECT) == SQLITE_OK) {
NSLog(@"database opened successfully");
}