1

我将 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);
}
4

1 回答 1

1

不幸的是,没有CFAutorelease。如何更改缓存检索方法的名称以使您明显地返回一个副本?

- (CGLayerRef) copyLayerForCacheKey: (CacheKey) key andProperty: (id) property;

那么即使是静态分析器也应该理解其中的区别。

于 2011-02-15T07:37:52.487 回答