如何将NSMutableArray用作UITableView的DataSource

Coc*_*Dev 5 uitableview nsmutablearray iphone-sdk-3.0 ios4 ios

我有一个带有数据的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;
}
Run Code Online (Sandbox Code Playgroud)

数据不会出现在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;
}
Run Code Online (Sandbox Code Playgroud)

Wri*_*sCS 5

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

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
Run Code Online (Sandbox Code Playgroud)

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

输出:哪个应该按照您的示例返回cell.textLabel.text

数:3,数组:("一","二","三")

您还应确保在标头中设置UITableViewDelegateUITableViewDataSource协议.