我要做的是以下内容:
用户在我的数据库中看到填充了现有记录的tableview; < -everything this here
用户触摸+按钮添加条目,并使用文本字段和按钮获得另一个非常简单的视图。
在我的按钮的IBAction方法中,我使用此代码向我的“DbOperations”类发送消息,其中插入应该发生:
DbOperations * med = [[DbOperations alloc] init]; [med InsertMedicine:self.txtMedicina.text];
用户然后返回到tableview并立即看到新条目。但是......没有写入数据库!
这是将条目插入db:
的方法- (void)InsertMedicine:(NSString *) med {
//Check to see if the new medicine already exists
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;
sqlite3 *dbase;
const char *sql = "SELECT * FROM listamedicine";
BOOL response= NO;
NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([database UTF8String], &dbase);
sqlite3_prepare_v2(dbase, sql, -1, &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW) {
if ([med caseInsensitiveCompare:[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)]] == NSOrderedSame) {
response=YES;
}
}
sqlite3_finalize(stmt);
if (!response) {
//Insert the new medicine
sqlite3_stmt *stmt=nil;
NSString *stmsql = [NSString stringWithFormat:@"INSERT INTO listamedicine (nomemedicina) VALUES (\"%@\")", med];
const char *sql2 = [stmsql UTF8String];
sqlite3_prepare_v2(dbase, sql2, -1, &stmt, NULL);
sqlite3_step(stmt);
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Errore"
message:@"La medicina che stai cercando di inserire esiste già."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
sqlite3_finalize(stmt);
sqlite3_close(dbase);
}
这是我的tableview用来填充单元格的代码:
- (NSMutableArray *)listMedicine {
fileMgr = [NSFileManager defaultManager];
sqlite3_stmt *stmt=nil;
sqlite3 *mybd=NULL;
const char *sql = "SELECT * FROM listamedicine";
NSMutableArray *listaMedicine = [[NSMutableArray alloc]init];
//Open db
NSString *database = [self.GetDocumentDirectory stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([database UTF8String], &mybd);
sqlite3_prepare_v2(mybd, sql, -1, &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW) {
Medicina *myMedicine = [[Medicina alloc]init];
myMedicine.dataId=[[NSNumber numberWithInt:(int)sqlite3_column_int(stmt, 0)] intValue];
myMedicine.nome=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
[listaMedicine addObject:myMedicine];
}
sqlite3_finalize(stmt);
sqlite3_close(mybd);
return listaMedicine;
}
这位于我的“DbOperations”课程中。 tableview中的cellForRowAtIndexPath方法如下所示:
static NSString *CellIdentifier = @"CellaMedicina";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellaMedicina"];
}
//Get the object from the array.
DbOperations *med = [[DbOperations alloc] init];
self.medicine = [med listMedicine];
Medicina *medicina = [self.medicine objectAtIndex:indexPath.row];
cell.textLabel.text = medicina.nome;
// Set up the cell
return cell;
我做错了什么?
答案 0 :(得分:0)
好的,我终于解决了这个问题...... 我有一个方法将db从bundle复制到文档文件夹,但我没有在任何地方调用它。