How to do some stuff in viewDidAppear only once?

2019-01-06 15:46发布

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 only invoked once, but the problem is that the alert view shows too quickly. I know I can set a timer to defer the alert's appearance, but it's not a good work-around I think.

I checked the question iOS 7 - Difference between viewDidLoad and viewDidAppear and found that there is one step for checking whether the view exists. So I wonder if there's any api for doing this?

Update: The "only once" means the lifetime of the view controller instance.

7条回答
相关推荐>>
2楼-- · 2019-01-06 16:29

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];
查看更多
登录 后发表回答