当我的应用程序返回到前台时,在我的视图中调用方法

时间:2013-04-01 17:22:36

标签: ios uiviewcontroller

当我的应用程序从后台返回时,如何调用方法?

我知道有些方法可以在app delegate中调用,但我想在我的视图中调用一个方法。

这样做的最佳方式是什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您应该拥有所需的视图控制器注册UIApplicationWillEnterForegroundNotification通知,例如initWithNibName:nibBundleOrNil:

- (id)initWithNibName(NSString *)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethod:) name:UIApplicationWillEnterForegroundNotification object:nil];

        // Whatever else your init method should do here...
    }    

    return self;        
}

- (void)yourMethod:(NSNotification *)notification
{
    // whatever you want to do here...
}

确保您还在dealloc中取消注册:

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}