【问题标题】:refreshing NSTableView with new data multiple times多次使用新数据刷新 NSTableView
【发布时间】:2010-01-17 00:53:55
【问题描述】:

我有一个 NSMutableArray 并从中加载我的 tableview。现在我在 UI 中有一个按钮,它可以让用户多次刷新进入数组的数据。 每次数组中有新数据时,我都想刷新 tableView。 只是在更新数组后做 [tableView reloadData] 似乎带来了沙滩球。 关于什么是实现这一目标的好方法的任何想法?

我也一直在研究绑定作为从数组中实现我的 NSTableView 的一种方式,但是在线显示的所有示例在他们想要将数据添加到他们的表时都使用绑定? 谁能指出我如何使用 Bindings 将包含数据的数组加载到 tableView 中?

对不起,如果问题是新手问题,如果有人可以指出正确的数据,我愿意阅读。谢谢:)(我不是在寻找捷径,只是想从有经验的人那里获得一些关于如何处理这些事情的建议)

-(IBAction)refreshList:(id)sender
{
//setup array here and sort the array based on one column. This column has 
  identifier 'col1' and it works as expected


[aTable reloadData];
  } 

- (int) numberOfRowsInTableView:(NSTableView *)aTable
{ // return count of array
 }

- (id)tableView:(NSTableView *)aTable objectValueForTableColumn: (NSTableColumn *)          
tableColumn row:(int)row
 { 
 //set up arrays here to load data in each column


 }
- (void)tableView:(NSTableView *)aTableView sortDescriptorsDidChange:(NSArray   
 *)oldDescriptors
 {
 //sort here when column headers are clicked
 } 

 -(IBAction)autorefresh:(id)sender
   {

 // Here i am trying to reload the array and refresh the tableView. I want to       
  constantly keep refreshing the array and loading the tableView here. The array does 
  get   refreshed but I am having trouble loading the tableView.


  for ( int i =0; i<=2;i++)
  { 
     // reload the array with data first.
  [aTable reloadData];
    i = 1;

  } 

【问题讨论】:

  • 欢迎来到 SO。请正确标记您的问题:)

标签: objective-c cocoa nstableview


【解决方案1】:

使用该代码(尤其是您非常新颖的“while true”循环),您会得到一个沙滩球,因为您永远不会回到 man 运行循环。在设置 NSTableView 后修复使用这样的代码,它将每 1.0 秒运行一次

NSTimer* timer = [NSTimer timerWithTimeInterval:1.0
                                         target:[NSApp delegate]
                                       selector:@selector(myReloadData:)
                                       userInfo:nil
                                        repeats:YES];

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];  

然后在您的应用委托中创建 myReloadData

- (void)reloadMyData:(NSTimer*)ntp
{
  // reload the array with data first.
  [aTable reloadData];
}

【讨论】:

  • > 你非常新颖的“while true”循环不只是正确的答案,也写得很好。
【解决方案2】:

如果-reloadData 引起了一个沙滩球,几乎可以肯定意味着您的控制器对NSTableDataSource 协议的实现存在问题。您需要弄清楚为什么会发生这种情况并解决它。如果您发布表格数据源代码,那么也许我们可以帮助您找出原因。

我强烈建议您在查看绑定之前先熟悉“标准”NSTableView 数据源和委托方法。 Cocoa Bindings 是一个相对高级的主题,听起来您需要更多基本的 Cocoa 经验才能继续进行绑定。

也就是说,这个页面有一套全面的 Cocoa 绑定示例:

http://homepage.mac.com/mmalc/CocoaExamples/controllers.html

自您发布代码后更新:

我不得不假设您在上面的代码中故意省略了数据源方法的实现,因为您发布的代码不会在没有警告的情况下编译。

您的自动刷新方法是一个无限循环。这将解释沙滩球。您在循环的每次迭代中将 i 设置为 1,这意味着永远不会达到结束条件。

但是,像这样使用for 循环是一种非常糟糕的刷新表格视图的方法,并且会阻塞主线程。如果您需要定期重复更新表格视图,请使用以指定间隔调用的NSTimer

【讨论】:

  • 谢谢 irsk。我一定会多读书。我添加了上面的代码。有什么想法吗?
  • 哎呀,愚蠢的错误。知道了。我实现了 NSTimer,它按预期工作。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多