Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

ios - How to prevent notitifcation observer from being called after UIViewController is popped?

I have 2 UIViewController A and B. From A I pushed B and B has 2 observers for reachability. Now when I pop B and comes to A after this if Network goes off then the method written in VC B is called. I'm unable to figure it out that if B is already popped from navigation stack how it's method is called ?

Note -

  1. I'm not having any property for VC B in VC A. Im always creating a new instance of VC B whenever pushing from VC A.
  2. I also know I can remove observer in viewWillDisappear but still I want to know why observer is called even after the VC B is popped.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about if you use a flag that you switch on in viewWillAppear and off in viewWillDisappear and also in other relevant places e.g. in isMovingFromParentViewController or what applies based on how you present it. Then you can flag your action when the observer triggers. Here is an outline.

@interface ViewController ()

@property (nonatomic) BOOL flag;

@end

@implementation ViewController

// Action triggered by observer
- ( void ) someAction
{
    if ( self.flag )
    {
        // do it
    }
}

// Switch on
- ( void ) viewWillAppear:( BOOL ) animated
{
    [super viewWillAppear:animated];
    self.flag = YES;
}

// Switch off
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.flag = NO;
}

@end

This is pretty simple. It is easy to maintain and debug and also if you need to at some stage switch on or off the action based on some other reason, it is easy to accommodate.

PS : You really need to show some code ... it is difficult to give more specific answer without you giving any code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...