2011-02-15 2 views
1

J'ai CGLayers mises en cache dans un NSMutableDictionary où je les utilise comme suit:Comment lier automatiquement un CGLayer?

- (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]; 
} 

Je crois avoir une fuite de mémoire ici en ne CGLayerRelease'ing returnedLayer de getLayerForCacheKey. Avons-nous une méthode dans laquelle ils peuvent être autoreleased?

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

Répondre

1

Malheureusement, il n'y a pas CFAutorelease. Que diriez-vous de changer le nom de la méthode de récupération du cache pour qu'il soit évident que vous renvoyez une copie?

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

Alors même l'analyseur statique devrait comprendre la différence.

Questions connexes