Clicky

iOS Dev Nugget 39 Use NSCache Instead of NSMutableDictionary When Caching

.

Need to run a code review on your codebase? Hire me

Often you'll want to cache objects in your app. You might do it for many reasons such as avoiding expensive calculations or to reducing unnecessary network access. If you are using NSMutableDictionary for this, you'll definitely want to look into NSCache for caches.

The key benefit of NSCache over NSMutableDictionary when used as a cache is the former will automatically evict objects from itself appropriately when there's low memory pressure.

Using NSCache is easy. If you don't use subscript-indexing syntax for NSDictionary/NSMutableDictionary, you'll cover almost all cases by just replacing NSMutableDictionary with NSCache.

If you use subscript-indexing, you can add the following extension:

@interface NSCache(NSCache_extension)

- (id)objectForKeyedSubscript:(id)key;
- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key;

@end

@implementation NSCache(NSCache_extension)

- (id)objectForKeyedSubscript:(id)key {
    return [self objectForKey:key];
}

- (void)setObject:(id)object forKeyedSubscript:(id<NSCopying>)key {
    [self setObject:object forKey:key];
}

@end


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues