如何告诉viewcontroller从另一个类更新其UI

时间:2014-01-08 18:07:52

标签: ios objective-c

我试图了解当前可见的viewController的更新是如何工作的。 我有ViewControllerAClassA。我想告诉ViewControllerA来自tableview的{​​{1}}重新加载数据。这样做的最佳方法是什么?

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

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:2)

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

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

另一个是视图控制器使用KVO观察模型更改。 (请参阅herehere)。

经常被忽视的另一个好的,可能在你的情况下使用的是“几乎什么都不做”的模式。在viewWillAppear时,只需在表视图上重新加载数据。

答案 2 :(得分: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的优势在于他们可以在多个类中添加观察者。