如何自动发布CGLayer?

时间:2011-02-15 06:52:34

标签: iphone memory-leaks autorelease cglayer

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

我认为我的内存泄漏不是来自 getLayerForCacheKey 的CGLayerRelease'ing returnedLayer 。我们有什么方法可以自动释放它们吗?

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);
}

1 个答案:

答案 0 :(得分:1)

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

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

然后即使是静态分析仪也应该理解其中的差异。