将数据从数据库插入表

时间:2012-02-06 08:38:13

标签: iphone objective-c ios xcode uitableview

我想将数据从数据库插入到表中。 我能够从数据库中获取数据并将其插入表中,但只有最后一个数据插入到表的所有行中。我已将代码用作

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
     Action *actionInformation;

    if(cell == nil){


        cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 460) reuseIdentifier:@"MyIdentifier"] autorelease];

        PrepopulatedActionsDao * preAction = [[PrepopulatedActionsDao alloc] init];

        [preAction getDataFromDatabase];

        NSMutableArray *allPreActions=[preAction getDataFromDatabase];

        for(int i=0;i<[allPreActions count];i++){

            actionInformation=[allPreActions objectAtIndex:i];


            cell.textLabel.text = [NSString stringWithFormat: @"%@",actionInformation.action];

        }
    }
    return cell;
}

这里的PrepopulatedActionsDao是我从数据库获取所有数据的类。

我想在表中插入数据库的所有数据,而不仅仅是最后一个。 请任何人帮忙。

4 个答案:

答案 0 :(得分:1)

将为每一行调用cellForRowAtIndexPath,因此您需要在每次调用中提供正确的数据。因此,您可以执行

而不是&#34; for循环&#34;
actionInformation=[allPreActions objectAtIndex:[indexPath row]];
cell.textLabel.text = [NSString stringWithFormat: @"%@",actionInformation.action];

您可能还想缓存allPreActions,而不是在每次调用中填写它。

答案 1 :(得分:1)

不需要for循环。为tableview中的每一行调用cellforrow方法。所以你只需要输入以下行cell.textLabel.text = [NSString stringWithFormat: @"%@",[[allPreActions objectAtIndex:indexPath.row] action];而不是for循环。

希望这能解决你的问题。

答案 2 :(得分:0)

每次都会分配。所以在外面宣布。

PrepopulatedActionsDao * preAction = [[PrepopulatedActionsDao alloc] init];

[preAction getDataFromDatabase];
  NSMutableArray *allPreActions=[preAction getDataFromDatabase];

此外,您不需要循环,而是以这种方式执行:

    actionInformation=[allPreActions objectAtIndex:indexpath.row];
    cell.textLabel.text = [NSString stringWithFormat: @"%@",actionInformation.action];

答案 3 :(得分:0)

在.h文件中声明NSMutableArray成员allPreActions(将其声明为类成员)并在viewDidLoad之前或其他地方填充cellForRowAtIndexPath:

因此,此代码将出现在viewDidLoad

PrepopulatedActionsDao * preAction = [[PrepopulatedActionsDao alloc] init];

if( allPreActions )
{
   [allPreActions releaseAllObjects];
   [allPreActions release];
}

allPreActions = [[preAction getDataFromDatabase] retain];
[preAction release];

您的cellForRowAtIndexPath:将如下所示

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
    Action *actionInformation;

    if(cell == nil){
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 460) reuseIdentifier:@"MyIdentifier"] autorelease];
    }
    actionInformation=[allPreActions objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat: @"%@",actionInformation.action];

    return cell;
}
相关问题