MENU
コンテンツ再構築中

Objective-C:NSNotificationCenterでアプリ起動・終了時にメソッドを呼び出す

アプリ終了時に実行したい処理がある場合は、NSNotificationCenter を使う。

INDEX

NSNotificationCenterのサンプルコード

アプリが終了する直前に myFunction を実行
[code]
– (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationWillTerminateNotification
object:nil];
}
– (void)myFunction
{
NSLog(@”UIApplicationWillTerminateNotification selector”);
}
[/code]

その他の通知タイミング

UIApplicationDidBecomeActiveNotification

アプリがアクティブになったとき

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[/code]

UIApplicationDidEnterBackgroundNotification

アプリがバックグラウンドになる時

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[/code]

UIApplicationDidFinishLaunchingNotification

アプリケーションが起動した直後

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationDidFinishLaunchingNotification
object:nil];
[/code]

UIApplicationWillEnterForegroundNotification

アプリがアクティブになる直前

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[/code]

UIApplicationWillResignActiveNotification

アプリがアクティブで無くなる直前

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationWillResignActiveNotification
object:nil];
[/code]

UIApplicationWillTerminateNotification

アプリが終了する直前

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationWillTerminateNotification
object:nil];
[/code]

UIApplicationWillChangeStatusBarOrientationNotification

デバイスの向きが変わる直前

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationWillChangeStatusBarOrientationNotification
object:nil];
[/code]

UIApplicationDidChangeStatusBarOrientationNotification

デバイスの向きが変わった後

[code]
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(myFunction)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
[/code]

まとめ

アプリの状態に合わせて処理を行いたい場合には NSNotificationCenter は必須のオブジェクトですね。

Please share it!
  • URLをコピーしました!
  • URLをコピーしました!
INDEX