0

sqliteデータベースを正常に更新できますが、主キーをテーブルビューで選択した行に対応させたいと思います。私が苦労している理由は、テーブルビューからインデックスパスを取得し、それをデータベースを更新するTodoクラスに渡す必要があるためです。コードは次のとおりです。

Tableview(RootViewController):

- (void)updateStatus:(id)sender { // called when a user presses the button to alter the status

NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)[sender superview]];
NSLog(@"The row id is %d",  indexPath.row); // This works

todoAppDelegate *appDelegate = (todoAppDelegate *)[[UIApplication sharedApplication] delegate];
Todo *td = [appDelegate.todos objectAtIndex:indexPath.row];

self.selectedIndexPath = indexPath;
NSLog(@"Selected index path is %i", self.selectedIndexPath); 

if (td.status == 0) {       
    [td updateStatus:1];
    NSLog(@"Status is %i",td.status);
}
else {
    [td updateStatus:0];
    NSLog(@"Status is %i",td.status);
}

[appDelegate.todos makeObjectsPerformSelector:@selector(dehydrate)];
} 

Todoクラス:

- (void) dehydrate {
if (dirty) { // If the todo is “dirty” meaning the dirty property was set to YES, we will need to save the new data to the database.
if (dehydrate_statment == nil) {
    const char *sql = "update todo set complete = ? where pk= ?"; // PK needs to correspond to indexpath in RootViewController

    if (sqlite3_prepare_v2(database, sql, -1, &dehydrate_statment, NULL) != SQLITE_OK) {
        NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
    }
}

sqlite3_bind_int(dehydrate_statment, 2, self.primaryKey);
sqlite3_bind_int(dehydrate_statment, 1, self.status);
int success = sqlite3_step(dehydrate_statment);

if (success != SQLITE_DONE) {
    NSAssert1(0, @"Error: failed to save priority with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_reset(dehydrate_statment);
dirty = NO;
NSLog(@"Dehydrate called");
}       
}

どうもありがとう!!!

4

2 に答える 2

0

あなたのコードに関するいくつかのコメント:

  1. AppDelegate を使用してグローバルデータをホストする代わりに、シングルトン クラスを使用する必要があります。
  2. [appDelegate.todos makeObjectsPerformSelector:@selector(dehydrate)] を使用する; あなたがしたいことを見て複雑すぎます。dehydrateTodo を pk で対象とする方法が適しています。

あなたの質問について:

indexPath 行と pk の間に対応関係がない場合、Cell は主キー/todo データをホストして、それらを「リンク」できるようにする必要があります。

独自のセル サブクラスを作成したくない場合の簡単な方法の 1 つは、セルtagプロパティを使用することです。

于 2011-04-15T19:15:32.327 に答える
0

あなたのコードから、各 todo が同じ PK (indexPath.row) を取得すると想定する必要があります。

次のように、「performSelector」を分割し、各 todo にインデックスを渡します。

  for ( Todo *todo in appDelegate.todos ) {
        [todo dehydrate:indexPath.row];
   }

そして、脱水を次のように再宣言します。

     - (void) dehydrate:(int) primaryKey {  // use pk here ... }
于 2011-04-15T19:10:11.617 に答える