我是 Objective-C 和 Sqlite 数据库的新手。所以我不明白我的代码中的错误是什么。我正在做一个简单的待办事项列表。在第一页,我想显示所有的任务,并且在标题中,有一个添加按钮。当我们单击该按钮时,它将移动到第二个故事板。在那里,我们可以输入主任务和子任务。我创建了一个名为 TodolistView1Controller 的新页面,并在其中创建了数据库并将数据插入到数据库中。但我的问题是当我们回到主页时,它不会显示我们现在输入的新任务。我将粘贴下面的代码:-
在 TodolistView1Controller.m
-(void)viewDidLoad
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"todo.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS TODO (ID INTEGER PRIMARY KEY AUTOINCREMENT, MYTASK TEXT, SUBTASK TEXT)";
if (sqlite3_exec(todoDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
status.text = @"Failed to create table";
}
status.text = @"Created the database";
sqlite3_close(todoDB);
} else {
status.text = @"Failed to open/create database";
}
} - (IBAction)save:(id)sender {
[myTask resignFirstResponder];
[subTask resignFirstResponder];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO TODO (MYTASK, SUBTASK) VALUES (\"%@\", \"%@\")", myTask.text, subTask.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(todoDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = @"Contact added";
myTask.text = @"";
subTask.text = @"";
} else {
status.text = @"Failed to add contact";
}
NSLog(@"7");
sqlite3_finalize(statement);
sqlite3_close(todoDB);
}
在主 ViewController.m
-(void)viewDidLoad
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
NSLog(@"Display1");
if (sqlite3_open(dbpath, &todoDB) == SQLITE_OK)
{
NSLog(@"Display2");
NSString *querySQL = [NSString stringWithFormat:
@"SELECT MYTASK, SUBTASK FROM TODO "];
NSLog(@"Display3");
const char *query_stmt = [querySQL UTF8String];
NSLog(@"Display4");
if (sqlite3_prepare_v2(todoDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSLog(@"Display5");
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSLog(@"Display6");
NSLog(@"Data is displayed");
} else {
NSLog(@"Display7");
NSLog(@"Data cannot be displayed");
}
sqlite3_finalize(statement);
}
sqlite3_close(todoDB);
}
因此,每当我运行它时,我都会在控制台中获得输出 Display1、Display2、Display3 和 Display4。谁能告诉我为什么我没有得到输出 display5 和 display6。
提前致谢。