1

FMDBをラッパーとして使用してsqliteデータベースを使用しているiPadアプリがあります。データベースからデータを正常にクエリできます。ただし、executeUpdateを使用してデータを挿入しようとすると、メソッドは正しく起動します(つまり、エラーが発生せず、YESが返されます)が、実際にはデータベースに何も挿入されません。挿入したばかりのオブジェクトをすぐに取得しようとしましたが、nullです。また、挿入したテーブルの行数を調べてみましたが、テーブルは空です。私が間違っていることについて何か考えはありますか?コードの一部を次に示します。

--すべてのデータベース作業を処理するクラスのinitメソッド

    -(NSString *)getDbPath {    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        return [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"];
     }

    -(id)init {
        self = [super init];
        if(self) {
           database = [FMDatabase databaseWithPath:[self getDbPath]];
           [database open];
        }

       return self;
     }

--データベースをdocsディレクトリに移動するアプリデリゲートコード

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSString *docsPath = [documentsDirectory stringByAppendingPathComponent:@"iRecipeBox.db"];

        if ([fileManager fileExistsAtPath:docsPath] == NO) {
            NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"iRecipeBox" ofType:@"db"];
            [fileManager copyItemAtPath:resourcePath toPath:docsPath error:&error];
         }
         return YES;

}

-テーブルの1つにデータを挿入するコード

    recipeID = [NSNumber numberWithInt:newRecipeID];
    [database beginTransaction];
    NSArray *newRow = [[NSArray alloc] initWithObjects:recipeID,title, description, picFile, prepTime, cookTime, ovenTemp, nil];
    NSString *sql = @"insert into recipes (id, name, descr, picFile, prepTime, cookTime, ovenTemp) values (?, ?, ?, ?, ?, ?, ?)";
    NSLog(@"Before update, the number of args is %i", [newRow count]);

    if([database executeUpdate:sql withArgumentsInArray:newRow]) {
        [database commit];
        NSLog(@"the insert worked");
    } else {
        [database rollback];
        NSLog(@"the insert failed");
    }
4

1 に答える 1

1

[FMDatabase databaseWithPath:]は自動解放されたオブジェクトを返すため、ARCを使用していない場合は、それを保持する必要があります。

executeUpdate:の直後に[database lastError]をチェックし、何かが表示されているかどうかを確認します。

そして最後に、トランザクションが1回の挿入である場合、トランザクションを使用しても意味がありません。

于 2012-06-05T17:13:50.300 に答える