0

我可以成功更新我的 sqlite 数据库,但是我希望主键对应于 tableview 中选择的行。我挣扎的原因是因为我需要从 tableview 获取 indexpath 并将其传递给我更新数据库的 Todo 类。这是代码:

表视图(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)];
} 

待办事项类:

- (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

我必须从您的代码中假设每个待办事项都将获得相同的 PK(indexPath.row)。

将您的“执行选择器”分开,并传递每个待办事项索引,如下所示:

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

并重新声明脱水为:

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

关于您的代码的一些评论:

  1. 您应该使用单例类,而不是使用 AppDelegate 来托管全局数据
  2. 使用 [appDelegate.todos makeObjectsPerformSelector:@selector(dehydrate)]; 看你想做的事情太复杂了。dehydrate以 pk 为目标的方法会更好。

关于你的问题:

如果 indexPath 行和 pk 之间没有对应关系,您的 Cell 应该托管主键/待办事项数据,以便您“链接”它们。

如果您不想创建自己的单元子类,一个简单的技巧是使用单元tag属性

于 2011-04-15T19:15:32.327 回答