【问题标题】:How to reload TableView data from AppDelegate.m?如何从 AppDelegate.m 重新加载 TableView 数据?
【发布时间】:2012-05-07 14:52:24
【问题描述】:

我尝试从 AppDelegate.m 重新加载 TableView 数据,但没有成功。

这是代码(在 HomeViewController 中工作):

AppDelegate.m

...
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[self refreshTableData];
}

-(void)refreshTableData{

    UINavigationController *navController = [[self.tabBarController viewControllers] objectAtIndex:0];
    HomeViewController *home = [[navController viewControllers] objectAtIndex:0];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MYTable" inManagedObjectContext:home.context];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    [request setFetchBatchSize:20];

    [request setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"orderEnt" ascending:YES];

    NSArray *newArray = [NSArray arrayWithObject:sort];

    [request setSortDescriptors:newArray];

    NSError *error;

    NSMutableArray *results = [[home.context executeFetchRequest:request error:&error] mutableCopy];

    [home setArr:results];

    //NSLog(@"%@", home.arr);//here is showed correct data

    home.context = self.managedObjectContext;

    [home.myTableView reloadData];


}
...

有人知道如何从 AppDelegate.m 重新加载数据吗?

【问题讨论】:

  • 你为什么要在 appdelegate 中调用?
  • home.myTableView 是一个有效的对象吗?

标签: objective-c xcode uitableview


【解决方案1】:

你可以实现

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableViewData) name:@"ReloadAppDelegateTable" object:nil]; 

在你的 viewDidLoad() 方法和

- (void)reloadTableViewData{
  [self.myTableView reloadData];
}

在要重新加载数据的类中。

然后你发送这样的通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"ReloadAppDelegateTable" object:nil];

每当您想重新加载数据时。

多年 iOS 开发经验后的注意事项: 虽然这是一个非常简单和舒适的解决方案,但它并不是 100% 可靠的。在某些情况下,通知可能会延迟几秒钟。我强烈建议您为您的UITableViewController 创建一个快速可靠的代理连接。


【讨论】:

  • 此代码正在运行,但 TableView 中的数据未更改。你有什么想法为什么会这样?
  • 一切正常,都是我的错。我还没有将 od IB myTableView 连接到插座。 :)
  • 非常感谢!效果很好.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
相关资源
最近更新 更多