ios - 如何使用 NSMutableArray 作为我的 UITableView 的数据源

标签 ios uitableview iphone-sdk-3.0 ios4 nsmutablearray

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

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

- (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 *myArray = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];

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

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

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

您还应确保在 header 中设置了 UITableViewDelegateUITableViewDataSource 协议(protocol)。

关于ios - 如何使用 NSMutableArray 作为我的 UITableView 的数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4938383/

相关文章:

ios - 在 watchOS2 上只有声音和触觉的 Lo​​calNotification

ios - 如何使 TableView 单元格上的按钮调用正确的 tableView :cellForRowAtIndexPath?

crash - UITableView 崩溃而没有错误

iphone - iphone sdk 4.0 中按钮尺寸变小

ios - 当有多个部分时, TableView 是黑色的

ios - RxSwift 中的滑动窗口

iphone - 是否可以连续获取iPhone当前位置的经纬度

objective-c - UIView 子类绘制背景,尽管 drawRect 完全为空 : - why?

ios - UIStackView 设置 subview 的优先级

ios - 在 iOS 错误中解析 JSON 图像 url