我有 2 个文件 DatabaseViewController.h 文件
#import <UIKit/UIKit.h>
#import "sqlite3.h"
@interface DatabaseViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *status;
@property(strong,nonatomic) NSString *databasePath;
@property(nonatomic) sqlite3 *contactDb;
@end
另一个 DatabaseViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
//Buid the path for database file
_databasePath = [[NSString alloc]
initWithString:[docsDir stringByAppendingPathComponent:@"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *db_path = [_databasePath UTF8String];
if(sqlite3_open(db_path, &_contactDb) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
if (sqlite3_exec(_contactDb, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
_status.text = @"Failed to create table";
}
sqlite3_close(_contactDb);
} else {
_status.text = @"Failed to open/create database";
}
}
}
不幸的是,声明
if(sqlite3_open(db_path, &_contactDb) == SQLITE_OK)
永远不会成功。
它只是路由到
_status.text = @"Failed to open/create database";
问题是什么?
我确实将 libsqlite3.dylib 添加到项目中。我正在使用 Xcode 4.5。