使用数组填充表视图的正确方法?

时间:2012-04-09 16:32:58

标签: iphone objective-c ios cocoa-touch

我正在尝试在我的iPhone应用程序上实现一个表视图,该应用程序从一个表视图/类中获取数组,并使用此数组在另一个单独的视图中填充表。这是我使用的方法,如果点击/点击它,就会向数组添加练习:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *str = cell.textLabel.text;
    NSUInteger *index = 0;

    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array insertObject:str atIndex:index];

    self.workout = array;

    [array release];
}

按下保存按钮后,此数组将存储在我想要在另一个视图中填充的训练数组(数组)中。我采取了正确的方法吗?

这是我的cellForRowAtIndexPath方法:

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];

    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier ];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier: SectionsTableIdentifier ] autorelease];
    }

    cell.textLabel.text = [nameSection objectAtIndex:row];
    return cell;
}

1 个答案:

答案 0 :(得分:1)

您可能不希望每次都使用新数组重新初始化self.workout

-(void) viewDidLoad
{
  self.workout = [[NSMutableArray alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *str = cell.textLabel.text;
    [self.workout insertObject:str atIndex:0];
}