gpt4 book ai didi

iphone - SQLite 数据库未更新

转载 作者:行者123 更新时间:2023-11-28 22:43:18 25 4
gpt4 key购买 nike

我有一个包含学生实体的数据库:

create table student ( name varchar(20) not null,
surname varchar(20) not null,
studentId integer primary key );

在我的应用程序委托(delegate)中,当应用程序启动时,我从数据库中加载所有元组并将它们显示到 TableView 中。
当应用程序委托(delegate)接收到 applicationWillResignActive 事件时,它会将所有元组保存到数据库中。它只保存已添加的元组,无法编辑元组,所以没关系。
当应用程序委托(delegate)收到 applicationWillEnterForeground 事件时,它会从数据库中读取元组。

问题:这只在应用程序的单次启动中起作用。假设我通过 Xcode 启动应用程序,然后我输入我添加一个元素并进入后台。之后我重新激活应用程序,它进入前台,并成功加载所有元组。
但是在下一次启动应用程序时(从 lldb 停止它并再次启动它),元组与第一次启动之前相同。

我为名为 Student 的学生实体创建了一个包装类,具有以下属性:

@property (nonatomic, copy, readwrite) NSString* name;
@property (nonatomic, copy , readwrite) NSString* surname;
@property (nonatomic, strong, readwrite) NSNumber* studentId;
@property (nonatomic, readwrite, getter= isNew) BOOL new;

我检查字段不为空并且实体完整性没有被破坏。
我使用的唯一有意义的方法是:

- (NSString*) sqlInsertionString;

它创建了插入元组所必需的字符串。经过测试并且有效。

这就是我更新数据库的方式:

- (void) updateStudents : (NSMutableArray*) students
{
sqlite3* database;
sqlite3_stmt* statement;
BOOL needsFinalize=NO;
if(!databasePath)
{
NSBundle* bundle=[NSBundle mainBundle];
databasePath= [bundle pathForResource: @"test" ofType: @"db"];
}
if(sqlite3_open([databasePath UTF8String], &database)!=SQLITE_OK)
{
NSString* problem= [NSString stringWithFormat: @"%s",sqlite3_errmsg(database)];
@throw [NSException exceptionWithName: @"Failed to open the database" reason: problem userInfo: nil];
}
for(Student * s in students)
{
if(s.isNew)
{
NSString* sqlString= [s sqlInsertionString];
if(sqlite3_prepare_v2(database, [sqlString UTF8String], -1, &statement, NULL)!= SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Problem performing the query" reason: @"Unknown" userInfo: nil];
}
if(sqlite3_step(statement)!=SQLITE_DONE)
{
@throw [NSException exceptionWithName: @"Problem performing the query" reason: @"Unknown" userInfo:nil];
}
sqlite3_reset(statement);
needsFinalize=YES;
}
}
if(needsFinalize && sqlite3_finalize(statement)!=SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Failed to close the statement resource" reason: @"Unknown" userInfo:nil];
}
if(sqlite3_close(database)!= SQLITE_OK)
{
@throw [NSException exceptionWithName: @"Failed to close the database" reason: @"Unknown" userInfo: nil];
}
}

但它并没有真正更新,只是在应用程序内部它似乎被更新了,但文件始终保持不变。

最佳答案

问题是您从包中打开数据库。您不能对其进行(持久)修改。标准解决方案是检查 Documents 文件夹中的数据库,如果存在,则使用它,如果没有,则从 bundle 复制到 Documents,然后从 打开数据库>文档

参见 Unable to connect SQLite Database in iOS

关于iphone - SQLite 数据库未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com