Graphics Programs Reference
In-Depth Information
More on Low-Memory Warnings
You have seen how view controllers handle low-memory warnings - they are sent the mes-
sage didReceiveMemoryWarning and destroy their views if they are not on the
screen. This is an appropriate solution to handling a low-memory warning: an object gets
rid of anything it isn't currently using and can recreate later. Objects other than view con-
trollers may have data that they aren't using and can recreate later. The BNRImageStore
is such an object - when its images aren't on the screen, it is okay to destroy them because
they can be loaded from the filesystem when they're needed again.
Whenever a low-memory warning occurs, UIApplicationDidRe-
ceiveMemoryWarningNotification is posted to the notification center. Objects
that want to implement their own low-memory warning handlers can register for this noti-
fication. In BNRImageStore.m , edit the init method to register the image store as an
observer of this notification.
- (id)init
{
self = [super init];
if (self) {
dictionary = [[NSMutableDictionary alloc] init];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(clearCache:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
Now, a low-memory warning will send the message clearCache: to the
BNRImageStore instance. In BNRImageStore.m , implement clearCache: to re-
move all the UIImage objects from the BNRImageStore 's dictionary .
- (void)clearCache:(NSNotification *)note
{
NSLog(@"flushing %d images out of the cache", [dictionary count]);
[dictionary removeAllObjects];
}
Search WWH ::




Custom Search