2011-02-07 97 views
0

我有一个UITableView,我想通过定时器调用的方法进行更新。我现在拥有的是:连续填充tableview

-(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 = arrayviewDidLoad它的工作原理,但不会重复。我的方法populateTable正在被调用,但实际上并没有在桌子上放置任何东西。这是我第一次使用UITableView,所以我不太了解他们的工作方式。我按照教程做了很多。如何使用一种方法来填充数据?

+0

嘿 - 在这个老问题上,对于googlers这里是一个指向现代方法的指针http://stackoverflow.com/ a/25604378/294884希望它可以帮助某人 – Fattie 2014-09-03 08:21:34

回答

3

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

+0

我该怎么做? – Chris 2011-02-07 19:05:26

0

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

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

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

喜欢的东西

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

在这种情况下indexArray是IndexPaths的阵列,使在那里你数组中更新的信息。

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

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

btw。 IHMO最好你的模型是一个NSMutableArray你可以在其中添加一些东西。 在你的populateTable的实现中,你只需要替换你的数组。

PS:调用reloadData只

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