How to do some stuff in viewDidAppear only once?

前端 未结 8 1459
暖寄归人
暖寄归人 2020-11-29 03:25

I want to check the pasteboard and show an alert if it contains specific values when the view appears. I can place the code into viewDidLoad to ensure it\'s onl

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 04:07

    Try to set a BOOL value, when the situation happens call it.

    @interface AViewController : UIViewController
       @property(nonatomic) BOOL doSomeStuff;
    @end
    
    @implementation AViewController
    - (void) viewWillAppear:(BOOL)animated
    {
        if(doSomeStuff)
        {
           [self doSomeStuff];
           doSomeStuff = NO;
        }
    }
    

    in somewhere you init AViewController instance:

    AddEventViewController *ad = [AddEventViewController new];
    ad.doSomeStuff = YES;
    

    Not sure why you do this in ViewDidAppear? But if you want doSomeStuff is private and soSomeStuff was called only once, here is another solution by notification:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomeStuff) name:@"do_some_stuff" object:nil];
    
    - (void) doSomeStuff
    {}
    

    Then post when somewhere:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"do_some_stuff" object:nil];
    

提交回复
热议问题