When I started creating my caching class I was sure I'll use it always on the main thread but it turns out I need it in multiple threads because UIScrollView in tiled mode draws the tiles in background threads. So now I need my cache to be thread safe.
I had to solve two problems: One, mutable array/dictionary holding cached images, and two, returned objects could dissapear while being used in another thread.
Am I doing this right?
I had to solve two problems: One, mutable array/dictionary holding cached images, and two, returned objects could dissapear while being used in another thread.
Am I doing this right?
Code:
- (UIImage *)cachedImageForAddress:(NSString *)imgAddress
{
UIImage *retImage = nil;
@synchronized(self) {
retImage = [self.imageDictionary objectForKey:imgAddress];
}
return ([[retImage retain] autorelease]);
}
Code:
- (BOOL)cacheImage:(UIImage *)newImage forAddress:(NSString *)imgAddress
{
BOOL retVal = YES;
@synchronized(self) {
if (![self.imgDicKeys containsObject:imgAddress]) {
[self.imageDictionary setObject:newImage forKey:imgAddress];
[self.imgDicKeys addObject:imgAddress];
// See if thre's too many
[self trimImageDictionary:self.imageDictionary
withKeys:self.imgDicKeys
toMaxSize:kMaxImagesInCache];
}
else if (![self.imageDictionary objectForKey:imgAddress])
NSLog (@"Inconsistant image cache!");
else
retVal = NO;
}
return (retVal);
}