- init
{
if(![super init]) return nil;
//the database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingFormat:@"/base.sqlite"];
NSLog(@"%@",path);
db = [FMDatabase databaseWithPath:path];
[db setLogsErrors:YES];
if (![db open]) {
NSLog(@"Could not open db.");
return 0;
} else {
NSLog(@"DB Open....");
}
FMResultSet *rs = [db executeQuery:@"SELECT * FROM settings"];
return self;
}
这是我用来尝试从设置中访问数据的代码。 但是这会产生错误(我可以向你保证有一个设置表!)
这是来自终端的转储
BEGIN TRANSACTION;
CREATE TABLE About (id integer PRIMARY KEY AUTOINCREMENT,key varchar UNIQUE,value text);
DELETE FROM sqlite_sequence;
CREATE TABLE settings (version integer,updated timestamp,owner varchar);
INSERT INTO "settings" VALUES(1,'2009-05-11 14:29:07','boulevart');
COMMIT;
和错误:
2009-05-11 16:14:19.799 SummerGuide[9892:20b] /Users/andyjacobs/Library/Application Support/iPhone Simulator/User/Applications/762630F5-78CB-41A4-85C2-964316ACFE1D/Documents/base.sqlite
2009-05-11 16:14:19.801 SummerGuide[9892:20b] DB Open....
2009-05-11 16:14:19.804 SummerGuide[9892:20b] DB Error: 1 "no such table: settings"
2009-05-11 16:14:19.804 SummerGuide[9892:20b] DB Query: SELECT * FROM settings
奇怪的是,如果我改变我的路径,例如/baseeeeee.sqlite(这不是没有文件),它仍然说“DB Open ....”
我刚刚将一个现有的sqlite文件(base.sqlite)添加到我的recourse文件夹中,并将sqlite3 lib添加到我的框架中。
答案 0 :(得分:3)
要获取应用包中文件的路径,请使用以下命令:
[[NSBundle mainBundle] pathForResource:@"base" ofType:@"sqlite"];
要实际打开数据库,您可能必须先将其复制到Documents目录,因为尝试修改应用包中的文件是个坏消息。