【问题标题】:Add observers of UITableViewController bar button?添加 UITableViewController 栏按钮的观察者?
【发布时间】:2014-10-13 13:48:24
【问题描述】:

我有一个ViewController,它以NSTimers 开头。我将每个NSTimers 添加为UIApplicationDidEnterBackgroundNotification 的观察者,以便在应用程序进入后台时可以阻止它们。效果很好。

[[NSNotificationCenter defaultCenter]
addObserver:anotherTimer
selector:@selector(goBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];

....

- (void) goBackground {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self invalidate];
}

这就是问题所在:我还对UITableViewController 进行了子类化,以向我的每个 ViewControllers 添加一个条形按钮(“I”表示信息)。条形按钮打开另一个ViewController,其中显示有关应用程序的信息。就像应用程序进入后台时一样,我希望所有NSTimers 在用户点击条形按钮时停止。

有没有办法让NSTimers 观察用户何时点击条形按钮或ViewController 何时退出?

【问题讨论】:

    标签: ios uiviewcontroller uibarbuttonitem nsnotificationcenter


    【解决方案1】:

    答案比我想象的要容易得多。正确的方法是创建一个具有任意名称的新通知(例如,“infoButtonTapped”)并将所有 NSTimers 作为观察者添加到该通知。通知调用与应用程序进入后台时发送的通知相同的方法(“goBackground”):

    [[NSNotificationCenter defaultCenter]
    addObserver:aTimer
    selector:@selector(goBackground)
    name:@"infoButtonTapped"
    object:nil];
    

    用户点击信息栏按钮时调用的方法发布同名通知:

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

    然后所有 NSTimers 的 goBackground 方法都会在 info Bar Button 被按下时被调用。

    请注意,我为 NSTimer 创建了一个类别,其中包括 setObservers、removeObservers 和 goBackground 方法,它们可以很好地处理通知。

    我还应该注意,每当一个 NSTimer 失效时(无论是在 goBackground 还是其他地方),它必须首先作为所有通知的观察者被删除:

    [aTimer removeObservers];
    [aTimer invalidate];
    

    否则,当发送这些通知之一时,应用程序将崩溃...

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      相关资源
      最近更新 更多