UITableView没有重新加载。

4

我正在制作一个使用 UITableViewUITableViewController 的应用程序。然而,当我在 UITableViewController 中调用 [self.tableView reloadData]; 时,什么也没有发生(tableView: cellForRowAtIndexPath: 没有被调用)。我该怎么办?

- (void) UserChangedAmmountAndCurrency: (NSNotification*) notification {
    self.localBank.activeAmmount=((NSNumber*)[notification.userInfo objectForKey:@"newAmmount"]).doubleValue;
    self.localBank.activeCurrency=[self.localBank.worldBank requestCurrencyForLocalBank:((NSString*)[notification.userInfo objectForKey:@"newISO4217Currency"])];
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSNumber *ammount= [self.localBank ammountForElementAtIndex:indexPath.row];
    VIPCurrency* currency=[self.localBank currencyForElementAtIndex:indexPath.row];


    static NSString *CellIdentifier = @"cellWithCurrencyAndAmmount";
    VIPConversionCell* cell=[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.longCurencyIdentifier.text=currency.longName;
    cell.shortCurrencyIdentifier.text=currency.shortName;
    cell.textfieldForAmmount.text=ammount.stringValue;
    return cell;
}

编辑:我做了一些额外的测试。我测试了tableview数据源和代理是调用reload方法的视图控制器,这很好。我还注意到了一些其他奇怪的事情。当调用reloadData时,既没有调用numberOfSectionsInTableView:也没有调用numberOfRowsInSection:。我觉得在调用reloadData之前我可能没能做一件基本的事情,但我不知道是什么。难道我必须以某种方式明确地将单元格设置为过时吗?

编辑:我还检查了该方法是否在主线程中调用,这也很好。


3
您的代码在dequeueReusableCellWithIdentifier返回nil时无法处理该情况... - verec
Verec,如果dequeueReusableCellWithIdentifier返回nill,我有没有理由从这个方法中返回其他东西?我认为如果是这种情况,那么肯定会有一个bug。在这里处理nill的情况是否有不同的哲学? - Blasmo
我已经使用Log函数进行了明确的检查,视图的数据源被正确设置,而且视图本身也非常活跃... :( - Blasmo
是的,那也是连接的。(self==self.tableView.delegate && self==self.tableview.dataSource)是YES。 - Blasmo
@verec,如果您已经使用可重用标识符注册了一个nib,在iOS5+中,如果队列中没有可重用的单元格,UITableView会自动为您创建一个有效的单元格;因此指针永远不会是nil,您不需要处理它。 - holex
显示剩余10条评论
3个回答

0
检查dequeReusableCellWithIdentifier调用中的nil的想法是创建一个新单元并返回它。除非您之前使用给定的标识符创建了一个单元并将其放入可重用池中,否则该方法将返回nil。因此,正如@Verec所提到的那样,您应该检查nil并自己创建单元和返回

我在故事板中创建了标识符为原型单元格的单元格,因此当队列为空时,将创建并提供新单元格。 - Blasmo
1
不需要再检查 nil 了。根据 Apple 的说法,你应该使用 dequeueReusableCellWithIdentifier:forIndexPath: 而不是 dequeueReusableCellWithIdentifier:,但我注意到似乎并不重要。只要在 storyboard 中制作单元格,并且具有正确的标识符,它就应该可以工作。此外,OP 说第一次加载表格时没有问题。 - rdelmar
如果您已经使用可重用标识符注册了一个 nib,在 iOS5+ 中,如果队列中没有可重用的单元格,UITableView 将自动为您创建一个有效的单元格;因此指针永远不会是 nil,您无需处理它。 - holex

0

.xib文件和.h文件中设置表视图代理 (UITableViewDataSource, UITableViewDelegate)

[myTableView reloadData];


-2
您只需要添加 <\/p>。
UITableViewDataSource,UITableViewDelegate

在 .h 文件中

示例

@interface yourviewcontroller : UIViewController <UITableViewDataSource,UITableViewDelegate>

仅仅声明符合协议是没有任何影响的;它只意味着控制器可以成为表视图数据源/代理。提问者还必须将此控制器设置为相关表视图的数据源和代理。 - Peter Hosey

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