您的代码错误。这是我用来写的:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
[db open];
[db executeUpdate:@"INSERT INTO foo (bar) VALUES (?)", bar];
[db close];
阅读:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
[db open];
NSMutableArray *bar = [[[NSMutableArray alloc] init] autorelease];
FMResultSet *s = [db executeQuery:@"select * from foo"];
while ([s next]) {
[bar addObject:[s stringForColumn:@"bar"]];
}
NSLog(@"%@", bar);
[db close];
还可以查看我所在数据库的位置。我认为按照你的方式在模拟器上可以工作,但在设备上不行,因为沙盒等等。
祝你好运!
编辑:
把它放在你的应用委托中:
- (void)createEditableCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
然后从application:didFinishLaunchingWithOptions 运行该方法:
[self performSelector:@selector(createEditableCopyOfDatabaseIfNeeded) withObject:nil];
确保首先将数据库放入项目树中。