我想开发一个iOS应用程序,因此我正在学习ObjectiveC。我遵循了在应用程序中使用SQLite数据库的教程。(http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_7_Application)
我有以下用于打开和创建数据库的代码,但是它不起作用!我收到消息“无法打开或创建数据库”。有人可以告诉我怎么了吗?
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the patht to the database file
_databasePath = [[NSString alloc]initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:_databasePath] == NO) {
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK) {
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
_lblStatus.text = @"Failed to create table";
}
sqlite3_close(_contactDB);
} else {
_lblStatus.text = @"Failed to open or create database";
}
}
}
我已经包含了'libsqlite3.dylib'并将#import添加到H文件中。
在您的代码中,有一些错误
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
使用NSDocumentDirectory而不是NSDocumentationDirectory
我认为它将解决您的问题。在我的建议下,您可以尝试核心数据。更简单了,您可以尝试一下本教程http://www.raywenderlich.com/934/core-data-tutorial-for-ios-getting-started
这真的很简单,很容易理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句