iOS シミュレータには「メモリ警告をシミュレート」という機能があるが、実機でも同様にメモリ警告を擬似的に発生させるにはどうすれば良いか考えた。
巨大な NSData 等を作ってメモリを消費するという力技もあるらしいが、それはちょっと怖い。
まず試したのは、自分で UIApplicationDidReceiveMemoryWarningNotification
を通知してみること。だがこれはうまくいかなかった。残念。
次に考えたのはメモリ警告時に実行されるプライベートメソッドがどこかにあるだろうかということで、それを調べるために適当な ViewController の didReceiveMemoryWarning
にブレークポイントを仕掛けて bt
2013-06-05 23:24:08.117 MyApp[5054:12203] Received memory warning.
2013-06-05 23:24:08.118 MyApp[5054:12203] -[MyViewController didReceiveMemoryWarning]
(lldb) bt
* thread #1: tid = 0x1f03, 0x0012fb1d MyApp`-[MyViewController didReceiveMemoryWarning] + 109 at MyViewController.m, stop reason = breakpoint 2.1
frame #0: 0x0012fb1d MyApp`-[MyViewController didReceiveMemoryWarning] + 109 at MyViewController.m
frame #1: 0x016cf60d UIKit`-[UIViewController _didReceiveMemoryWarning:] + 33
〜略〜
frame #5: 0x01f0b19a Foundation`-[NSNotificationCenter postNotificationName:object:userInfo:] + 98
frame #6: 0x01f17b03 Foundation`-[NSNotificationCenter postNotificationName:object:] + 55
frame #7: 0x0160ecf4 UIKit`-[UIApplication _performMemoryWarning] + 91
frame #8: 0x0160ee00 UIKit`-[UIApplication _receivedMemoryNotification] + 180
〜略〜
frame #18: 0x01604626 UIKit`UIApplicationMain + 1163
〜略〜
長いので一部略。
それっぽいものを発見:
[UIApplication _performMemoryWarning]
[UIApplication _receivedMemoryNotification]
とりあえず上のメソッドをセレクタで無理矢理呼び出してみる。
- (void)simulateMemoryWarning
{
UIApplication *app = [UIApplication sharedApplication];
if ([app respondsToSelector:@selector(_performMemoryWarning)])
[app performSelector:@selector(_performMemoryWarning)];
}
適当なところから simulateMemoryWarning
を実行したら、期待通り先ほどの didReceiveMemoryWarning
のブレークポイントに引っかかった。ちゃんと ViewController までメモリ警告の通知が行っている模様。
とりあえずめでたしめでたし?