需要NSNotification才能在iOS中使用整个应用程序

lak*_*esh 3 nsnotification ios

我需要检查整个应用程序中你的wifi状态是否已经改变.我正在使用Reachability检查wifi状态是否打开.

我已经建立了一个像这样的观察者:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
Run Code Online (Sandbox Code Playgroud)

问题是我需要将addObserver和removeObserver添加到所有viewcontrollers,并将reachabilityChanged函数添加到所有.

有没有更好的方法然后添加NSNotification我是否检查整个应用程序的无线状态?

需要一些指导和建议.谢谢.

Guo*_*uan 10

做一个super viewControllerrootViewControllersubClassUIViewController,并在init给init Notification,并在dealloc去除Notification

然后你viewController应该做subClass的一切rootViewController.它只是OOP

喜欢 :

@interface RootViewController : UIViewController

@end

@implementation RootViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (id)init
{
    self = [super init];
    if (self) {

        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];

    }
    return self;
}
- (void)reachabilityChanged:(NSNotification *)notification
{
    // you can do nothing , it should be override.
}
Run Code Online (Sandbox Code Playgroud)

当你创建你的viewController时,你应该继承 RootViewController

@interface YourViewController : RootViewController

- (void)reachabilityChanged:(NSNotification *)notification
{
    // if your super class method do some things you should call [super reachabilityChanged:notification]
    // do your thing.
}

@end
Run Code Online (Sandbox Code Playgroud)

implementation你应该实现的reachabilityChanged:方法

  • 好主意!但它不是一个完美的解决方案,想想你是否想从一个类继承而不是直接继承自UIViewController(例如UITableViewController).在appdelegate中添加通知观察器可能更好.然后遍历viewcontroller堆栈中的所有viewcontrollers,并向viewcontrollers发送一条消息,该视图控制器可以响应该方法. (2认同)