Objective c 使用NSFileManager时的SQLite问题
我使用的是SQLite,之前的回答说明我应该使用以下代码:Objective c 使用NSFileManager时的SQLite问题,objective-c,sqlite,Objective C,Sqlite,我使用的是SQLite,之前的回答说明我应该使用以下代码: #import "ViewController.h" @interface ViewController () { NSMutableArray *arrayOfPerson; sqlite3 *personDB; NSString *dbPathString; } @end @implementation ViewController - (void)viewDidLoad { [super vi
#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *arrayOfPerson;
sqlite3 *personDB;
NSString *dbPathString;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
arrayOfPerson = [[NSMutableArray alloc]init];
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
[self createOrOpenDB];
}
- (void)createOrOpenDB
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:@"persons.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager fileExistsAtPath:dbPathString];
NSLog(@"here 0");
if (!success) {// THIS IS MY CONCERN
const char *dbPath = [dbPathString UTF8String];
NSLog(@"here 1");
//creat db here
NSLog(@"sqlite3 = %d",sqlite3_open(dbPath, &personDB));
NSLog(@"OK= %d", SQLITE_OK);
if (sqlite3_open(dbPath, &personDB)==SQLITE_OK) {
NSLog(@"here 2");
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
sqlite3_exec(personDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(personDB);
}
}
}
但是,当我运行此代码时,我的应用程序不会进入此循环:
if(!success) {
....
}
我试着用
if(success) {
....
}
它是有效的。但我认为这是不对的。请帮助我。在
BOOL success=[fileManager fileExistsAtPath:dbPathString]添加断点
要检查此时发生的情况,如果您不喜欢,您需要提前将其中断。顺便说一下,您在这里打开了数据库两次!在NSLog
语句中执行一次,然后在if
语句中执行一次。确保你只打一次电话。另外,方法名也有误导性,因为它被称为createoropenb
,但它只是在不存在的情况下创建数据库。但它并没有打开数据库(尽管有前面提到的bug)。但是如果fileExistsAtPath
返回TRUE
,那么这就意味着您已经在那里拥有了一个数据库。