I have an iPhone app which deals with a subset of 25,000 places at any given time.
I'd like to maintain a cache of places so that I know that if one part of my application updates a place, every other part that knows about that place sees the update.
My nieve implementation is create an NSMutableSet to store references to the cached places.
Methods that find new places will first check the cache and return the cached object or if the place isn't in the cache, they will create a new place object and add it to the cache.
The problem is how do I release objects that are no longer needed?
The NSMutableSet will retain the place so the retainCount will never go to zero and dealloc will never be called.
I've thought about overriding release:
static NSMutableSet *cachedPlaces;
@implementation Place
- (void)release {
if (self.retainCount == 1) {
//I'm only being retained by the cache!
[cachedPlaces removeObject:self];
[self release];
}
[super release];
}
@end
But the apple documentation seems to strongly discourage overriding the release method.
The other way seems to be to garbage collect the cache, maybe when I get a low memory warning:
+ (void)garbageCollectCache {
NSMutableSet *garbagePlaces = [[NSMutableSet alloc] init];
Place *place;
for (place in cachedPlaces) {
if ([place retainCount] == 1) {
[garbagePlaces addObject:place];
}
}
for (place in garbagePlaces) {
[cachedPlaces removeObject:place];
}
[garbagePlaces release];
}
But this has blocks adding of objects to the cache and could cause delays in my UI.
Is there a kosher method to handle the release scenario? Is there some other pattern for doing this that I'm not aware of.
(and CoreData is not an option at this point, but I understand that it handles this).
Thank you,