【问题标题】:Continuously populating a tableview不断填充表格视图
【发布时间】:2011-02-07 18:34:27
【问题描述】:

我有一个 UITableView,我想通过计时器调用的方法对其进行更新。我现在拥有的是:

-(void) populateTable {
NSLog(@"done");
NSArray *array = [[NSArray alloc] initWithObjects:@"ob 1",@"ob 2",@"ob 3",nil];
self.listData = array;
[array release];
}


- (void)viewDidLoad {
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(populateTable) userInfo:nil repeats:YES];
[super viewDidLoad];
}

#pragma mark -
#pragma mark Table View Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}

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

static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:SimpleTableIdentifier] autorelease];
}

NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;

 }

如果我将数组和self.listData = array 放入viewDidLoad,它可以工作,但不会重复。我的方法populateTable 被调用,但实际上并没有在表中放入任何东西。这是我第一次使用 UITableView,所以我不太了解它们是如何工作的。我按照教程做了很多。如何使用方法填充数据?

【问题讨论】:

标签: objective-c cocoa-touch ios uitableview uikit


【解决方案1】:

你也应该在你的桌子上打电话给reloadData

【讨论】:

  • 留给后代:[[self tableView] reloadData];
【解决方案2】:

您需要将计时器添加到运行循环 - 现在您创建 NSTimer 对象,但由于它永远不会进入运行循环,因此它会触发一次并停止。在您的viewDidLoad 中尝试这样的操作:

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                   target:self
                                                 selector:@selector(populateTable)
                                                 userInfo:nil
                                                  repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

【讨论】:

    【解决方案3】:

    您必须通知您查看数组中的新条目。

    有点像

    [self.tableView insertRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationFade];

    在这种情况下,indexArray 是一个 IndexPaths 数组,它提供了更新数组的信息。

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];  
    

    之后视图会调用 tableView:cellForRowAtIndexPath: 方法来获取对象。

    顺便说一句。 IHMO 最好你的模型是NSMutableArray,你可以在其中添加一些东西。 在populateTable 的实现中,您只需始终替换您的数组。

    PS:只调用一个 reloadData

    ...当您分配新的数据源时。重新加载表格视图会清除当前状态,包括当前选择...(UITableView 类参考)

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多