【问题标题】:How to tell a viewcontroller to update its UI from another class如何告诉视图控制器从另一个类更新其 UI
【发布时间】:2014-01-27 00:06:32
【问题描述】:

我试图了解如何更新当前可见的viewController。 我有ViewControllerAClassA。我想告诉ViewControllerAClassA 重新加载tableview 上的数据。这样做的最佳方法是什么?

我找到了this 问题和答案,但我认为这不适用于我的情况,或者我没有正确理解它。

【问题讨论】:

  • 你的classA继承自什么??

标签: ios objective-c


【解决方案1】:

首选键值编码、NSNotificationCentre 和 Delegates。但 NSNotificationCentre 在你的情况下是最简单的。

包含 UITableView 的 UIViewController 必须像这样添加观察者: 初始化:

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

在delloc方法中:

  [[NSNotificationCenter defaultCenter] removeObserver:self];

从任何 XYZ 类发布它,就像在任何 UIButton 操作上一样:

[[NSNotificationCenter defaultCenter] 
        postNotificationName:@"TABLE_RELOAD" 
        object:self];

NSNotificationCentre 的优点是他们可以在多个类中添加观察者..

【讨论】:

    【解决方案2】:

    这里关于使用 NSNotificationCenter 的答案很好。请注意其他一些方法:

    常见的一种是委托模式(see herehere)。

    另一个是视图控制器使用 KVO 观察模型变化。 (见herehere)。

    另一个经常被忽视的好方法是“几乎什么都不做”模式。只需在 viewWillAppear 时重新加载表格视图上的数据即可。

    【讨论】:

      【解决方案3】:

      不知道您的设置的最简单方法是使用NSNotificationCenter。这是你可以做的:

      ViewControllerA 中添加NSNotificationCenter 的钩子:

      - (void)viewDidAppear:(BOOL)animated {
          [super viewDidAppear:animated];
      
          //Register for notification setting the observer to your table and the UITableViewMethod reloadData. So when this NSNotification is received, it tells your UITableView to reloadData
          [[NSNotificationCenter defaultCenter] addObserver:self.table selector:@selector(reloadData) name:@"ViewControllerAReloadData" object:nil];
      }
      
      - (void)viewWillDisappear:(BOOL)animated {
          [super viewWillDisappear:animated];
      
          //Need to remove the listener so it doesn't get notifications when the view isn't visible or unloaded.
          [[NSNotificationCenter defaultCenter] removeObserver:self];
      }
      

      然后在ClassA 中,当您想告诉 ViewControllerA 重新加载数据时,只需发布​​NSNotification

      - (void)someMethod {
          [[NSNotificationCenter defaultCenter] postNotificationName:@"ViewControllerAReloadData" object:nil];
      }
      

      【讨论】:

      • 这正是我想要的,感谢您提供如此简单的信息!
      • 没问题!很高兴我能帮助你。只要确保在可能的情况下接受它。
      猜你喜欢
      • 2021-10-21
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2011-05-10
      • 2019-02-15
      相关资源
      最近更新 更多