【问题标题】:How do I use a NSMutableArray as a DataSource for my UITableView如何使用 NSMutableArray 作为 UITableView 的数据源
【发布时间】:2011-02-08 21:00:46
【问题描述】:

我有一个带有数据的 NSMutableArray(硬编码)。

我实现了这两个 TableView 方法,并在 IB 中设置了委托和数据源

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [myArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];

    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];
    }

    cell.textLabel.text = [myArray objectAtIndex:[indexPath row]];
    NSLog(@"Cell is %@", [myArray objectAtIndex:indexPath.row]);
    return cell;
}

数据不会出现在 TableView 中。我已经运行了 NSLog,我可以看到数据在 myArray 中。

我将 NSLog 添加到代码中,但代码似乎永远不会执行。问题是我的数组是如何创建的?

这是代码

- (id)init:(NSMutableArray *)theArray
{
    [super init];
    countryTable.delegate = self;
    countryTable.dataSource = self;

    UITapGestureRecognizer * tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)] autorelease];
    [window addGestureRecognizer:tapRecognizer];

    myArray = [[NSMutableArray alloc] init]; 
    myArray = theArray;
    return self;
}

【问题讨论】:

  • 你是如何创建NSMutableArray的?

标签: ios uitableview iphone-sdk-3.0 ios4 nsmutablearray


【解决方案1】:

你的基本代码是正确的,只需要有一个数组(你没有在这里提供),所以这是一个例子:

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];

你可以NSLog这个:NSLog(@"Count: %i, Array: %@",[myArray count], myArray);

输出:应该以cell.textLabel.text 的形式返回根据您的示例

计数:3,数组:( “一”, “二”, “三” )

您还应该确保在标头中设置了UITableViewDelegateUITableViewDataSource 协议。

【讨论】:

    【解决方案2】:

    我不知道问题是否仍然存在,但我试一试。

    当我阅读您的代码时,我看不到 countryTable 的实例化位置,所以我认为它已在 InterfaceBuilder 中连接?如果是这种情况,countryTable 仅在 viewDidLoad 之后有效。 但是你也可以在 InterfaceBuilder 中设置委托和数据源。

    顺便说一句,每次更改数据源(myArray)时,调用 countryTable.reloadData。

    【讨论】:

      【解决方案3】:

      试试这个 -

      cell.textLabel.text = [[myArray objectAtIndex:indexPath.row] retain];
      

      【讨论】:

      • UILabel.text 是一个复制属性,额外的保留只会泄漏该 NSString。
      • 我尝试了保留和相同的问题。我将在上面发布我更新的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多