【发布时间】:2013-07-13 14:41:41
【问题描述】:
我想更新我的表格。此代码适用于模拟器,但不适用于设备。我发现我无法写入我的应用程序包中的任何文件,但我不知道如何改变它来工作。请帮帮我。
-(NSString *)filePath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir=[paths objectAtIndex:0];
NSError *error;
bool success;
NSString *writablePath = [documentsDir stringByAppendingPathComponent:@"Test.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:writablePath];
if(!success)
{
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Test.sqlite"];
success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
}
NSLog(@"%@",writablePath);
return writablePath;
}
然后:
- (IBAction)addToFavorite:(id)sender
{
[self filePath];
sqlite3_stmt *updateStatement=nil;
NSString *sql=[[NSString alloc]initWithFormat:@"UPDATE A SET favorite=? WHERE x='%@' ",mystring];
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &updateStatement, nil)==SQLITE_OK)
{
sqlite3_bind_text(updateStatement, 1, [@"1" UTF8String], -1, SQLITE_TRANSIENT);
}
if (sqlite3_step(updateStatement)!=SQLITE_DONE)
{
NSAssert(0,@"Error While Creating Update Statement. '%s'",sqlite3_errmsg(db));
}
sqlite3_reset(updateStatement);
}
【问题讨论】:
-
啊。我以前遇到过这个问题。复制你的 test.sqlite 数据库。将其重命名为 Test2.sqlite,然后将其复制回来。做一个清洁。更新你的源代码成为 test2.sqlite 并再次运行它。听起来很古怪,但这对我有用。
-
您通过将数据库从捆绑包复制到可写空间,或多或少找到了设置数据库的正确代码。您需要跟踪该代码的执行情况以找出问题所在。
-
设备区分大小写。如果您的文件确实命名为“Test.sqlite”而不是“test.sqlite”(或其他一些变体)?
-
您需要在
sqlite3_prepare_v2的支票上添加else。还要检查打开数据库的结果(之前使用sqlite3_open_v2)。 -
我在 Return writablePath 行中遇到错误。错误是“尝试写入只读数据库”