UITableViewController 没有被 NSMutableArray 填充

Posted

技术标签:

【中文标题】UITableViewController 没有被 NSMutableArray 填充【英文标题】:UITableViewController not being filled with NSMutableArray 【发布时间】:2014-03-29 17:09:34 【问题描述】:

我有一个表格视图控制器,FavoritesTableViewController,它有一个可变数组“citiesArray”。当按下城市按钮时,它会调用一个将对象添加到可变数组的方法。

[self.citiesArray addObject:@"New York"];

然后它会记录 self.citiesArray 的计数以及数组本身,并且似乎工作正常,这意味着它成功地将字符串“New York”添加到数组中。所以现在我有一个填充的可变数组并想用它填充表格视图。

这是我的代码,似乎不起作用。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
       UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
       if (cell==nil) 
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
       cell.textLabel.text=[self.citiesArray objectAtIndex:indexPath.row];
       return cell;

之后我尝试重新加载我的表格视图,但仍然无法正常工作。关于问题是什么的任何想法? 谢谢

【问题讨论】:

别忘了检查表视图委托。 @pawan,委托与此问题无关。如果 OP 没有设置数据源可能是问题,但委托方法与获取数据无关。 @rdelmar 我的错,我错误地写了委托,它应该是数据源。 【参考方案1】:

你必须添加方法来返回表中有多少行:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    return self.citiesArray.count;

【讨论】:

【参考方案2】:

实现方法:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    return 1;


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
    return self.citiesArray.count;

当然,如果您还没有设置表的datasourcedelegate 属性,您应该这样做,例如在ViewDidLoad 方法中:

- (void)viewDidLoad

    [super viewDidLoad];

    //....Your code....

    table.delegate = self;
    table.datasource = self;

【讨论】:

与@Greg 发布的相同。 numberOfSectionsInTableView: 如果您只有一个部分,则为可选。

以上是关于UITableViewController 没有被 NSMutableArray 填充的主要内容,如果未能解决你的问题,请参考以下文章

在 UITableViewController 中没有调用 viewWillAppear?

当我们使用 UITableViewController 的子类处理表委托时,如何使 viewWillAppear 被调用?

添加到 UITableViewController 时,SwiftUI 视图大小被破坏

UITableViewController 被释放

UITableView 没有重新加载

UITableViewController 没有响应键盘