如何将NSMutableArray用作UITableView的数据源?

5

我有一个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,可以看到数据在我的数组中。
我已经将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的? - WrightsCS
3个回答

5
您的基本代码是正确的,只需要有一个数组(您在此处未提供),因此这将是一个示例:
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];

你可以使用NSLog打印出如下内容:NSLog(@"Count: %i, Array: %@",[myArray count], myArray);

输出: 根据您的例子,应该将其作为cell.textLabel.text

Count: 3, Array: ( "One", "Two", "Three" )

同时,在头文件中设置UITableViewDelegateUITableViewDataSource协议。


1

我不知道这个问题是否还未解决,但我试着回答一下。

根据我阅读的代码,我没有看到countryTable被实例化的地方,所以我假设它是在InterfaceBuilder中连接的?如果是这样的话,在viewDidLoad之后countryTable才有效。 但你也可以在InterfaceBuilder中设置delegate和dataSource。

顺便说一下,每当你改变数据源(myArray)时,调用countryTable.reloadData。


0

试试这个 -

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

1
UILabel.text是一个拷贝属性,额外的retain只会泄漏该NSString。 - Jose Ibanez
我尝试了保留并且出现了相同的问题。我将在上面发布我的更新代码。 - Cocoa Dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接