我将 CGLayers 缓存在 NSMutableDictionary 中,并按如下方式使用它们:
- (CGLayerRef)getLayerForCacheKey:(CacheKey)cacheKey andProperty:(id)property {
NSDictionary *cacheDict = [cacheArray objectAtIndex:cacheKey];
if (cacheDict) {
NSValue *encodedLayer = [cacheDict objectForKey:property];
if (encodedLayer) {
CGLayerRef returnedLayer = nil;
[encodedLayer getValue:&returnedLayer];
return returnedLayer;
}
}
return nil;
}
- (void)saveLayer:(CGLayerRef)layer toCacheWithKey:(CacheKey)cacheKey andProperty:(id)property {
CGLayerRef layerToSave = CGLayerRetain(layer);
NSMutableDictionary *cacheDict = [cacheArray objectAtIndex:cacheKey];
NSValue *encodedLayer = [[NSValue alloc] initWithBytes:&layerToSave objCType:@encode(CGLayerRef)];
[cacheDict setObject:encodedLayer forKey:property];
[encodedLayer release];
}
我相信我在这里有内存泄漏,不是 CGLayerRelease从getLayerForCacheKey返回的层。我们有什么方法可以自动释放它们吗?
CacheKey key = CacheKeyFretNumberHighlight;
CGLayerRef numberLayer = [cacheManager getLayerForCacheKey:key andProperty:note];
// save to cache
if (!numberLayer) {
numberLayer = CGLayerCreateWithContext(nil, [numberStr sizeWithFont:font], nil);
CGContextRef numberLayerCtx = CGLayerGetContext(numberLayer);
UIGraphicsPushContext(numberLayerCtx);
CGContextSetFillColorWithColor(numberLayerCtx, highlightColor);
[numberStr drawAtPoint:CGPointZero withFont:font];
UIGraphicsPopContext();
[cacheManager saveLayer:numberLayer toCacheWithKey:key andProperty:note];
CGContextDrawLayerAtPoint(layerCtx, point, numberLayer);
CGLayerRelease(numberLayer);
} else {
CGContextDrawLayerAtPoint(layerCtx, point, numberLayer);
}