【问题标题】:Adding an observer to each view or present view dynamically将观察者添加到每个视图或动态呈现视图
【发布时间】:2013-07-22 07:44:43
【问题描述】:

每当我收到远程通知时,我都会在应用中本地发布通知。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"Received notification: %@", userInfo);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NEWMESSAGE" object:nil userInfo:userInfo]; }

我在函数 viewWillAppear() 中向视图添加了一个观察者,并在 viewWillDisappear() 中删除了观察者。

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

and
[[NSNotificationCenter defaultCenter] removeObserver:self];

我的问题是,我想覆盖在我的应用中使用这些函数的所有 *.m 文件中的每个 viewWillAppear 和 viewWillDisappear 函数。

或者我如何动态地将观察者(如上)添加到当前视图并在该视图消失时移除观察者。每当视图更改时,它应该就像一个全局动作,观察者在再次更改时被添加和删除。

这可能吗?如果是这样,请指导我。

提前致谢。

【问题讨论】:

  • 正如你所提到的,你想覆盖每个控制器中的 viewwillappear 和 viewwilldisappear 函数,这样做并在其中添加和删除观察者......不是问题所在。
  • 是的,有可能。你想做什么?你想达到什么目标?

标签: iphone ios objective-c ios4


【解决方案1】:

一些想法:

  • 您可以继承 UIViewController 并在子类化的视图控制器类中实现这些方法。然后你需要创建你所有的视图作为这个 UIViewController 的子类。

例子:

//Creating a custom subclass of UIViewController
@interface CustomViewController : UIViewController
@end

@implementation CustomViewController

 - (void)viewWillAppear:(BOOL)animated
{
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageReceived:) name:@"NEWMESSAGE" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

并将所有视图控制器创建为CustomViewController 的子类。

【讨论】:

  • @VardhanDG:很高兴 :) 一切顺利 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2013-06-01
  • 2011-09-07
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多