diff --git a/Source/PINMemoryCache.m b/Source/PINMemoryCache.m index 1442da0..93edd0c 100644 --- a/Source/PINMemoryCache.m +++ b/Source/PINMemoryCache.m @@ -175,6 +175,10 @@ - (void)removeObjectAndExecuteBlocksForKey:(NSString *)key PINCacheObjectBlock didRemoveObjectBlock = _didRemoveObjectBlock; [self unlock]; + if (object == nil) { + return; + } + if (willRemoveObjectBlock) willRemoveObjectBlock(self, key, object); @@ -239,13 +243,18 @@ - (void)trimToCostLimit:(NSUInteger)limit [self lock]; totalCost = _totalCost; - NSArray *keysSortedByCost = [_costs keysSortedByValueUsingSelector:@selector(compare:)]; [self unlock]; if (totalCost <= limit) { return; } + [self lock]; + NSDictionary *costs = [_costs copy]; + [self unlock]; + + NSArray *keysSortedByCost = [costs keysSortedByValueUsingSelector:@selector(compare:)]; + for (NSString *key in [keysSortedByCost reverseObjectEnumerator]) { // costliest objects first [self removeObjectAndExecuteBlocksForKey:key]; @@ -272,9 +281,11 @@ - (void)trimToCostLimitByDate:(NSUInteger)limit return; [self lock]; - NSArray *keysSortedByAccessDate = [_accessDates keysSortedByValueUsingSelector:@selector(compare:)]; + NSDictionary *accessDates = [_accessDates copy]; [self unlock]; + NSArray *keysSortedByAccessDate = [accessDates keysSortedByValueUsingSelector:@selector(compare:)]; + for (NSString *key in keysSortedByAccessDate) { // oldest objects first [self removeObjectAndExecuteBlocksForKey:key];