Search code examples
iosnsnotification

Need NSNotification to work through the whole app in iOS


I need to check whether your wifi status has changed throughout the whole app. I am using Reachability to check whether the wifi status is on.

I have set up an observer like this:

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

The problem is I need to add this addObserver and removeObserver to all viewcontrollers and the reachabilityChanged function to all.

Is there a better method then adding NSNotification whether I check the wifi status throughout the whole app?

Need some guidance and suggestions on this. Thanks.


Solution

  • make a super viewController called rootViewController to subClass the UIViewController and in the init to init the Notification and in the dealloc to remove the Notification

    And then all your viewController should subClass the rootViewController . It just OOP

    like :

    @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.
    }
    

    And when you creat your viewController , you should subclass the 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
    

    In the implementation you should achieve the reachabilityChanged: method