代码之家  ›  专栏  ›  技术社区  ›  Duck

IPHONE:释放对象后仍分配内存?

  •  0
  • Duck  · 技术社区  · 15 年前

    我有一种方法,可以使用石英将屏幕外的对象绘制到文件中。此方法的最后几行是:

    CGRect LayerRect = CGRectMake(mX,mY, wLayer, hLayer);
    CGContextDrawImage(objectContext, LayerRect, objectProxy.image.CGImage); // 1
    
    CGRect superRect = CGRectMake(vX, vY, w,h);
    CGContextDrawLayerInRect(context, superRect, objectLayer);
    
    CGLayerRelease(objectLayer); // 2
    UIImage * myImage = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext(); //3
    return myImage;
    

    所以,没有泄漏,对吗?

    我在“内存分配”选项卡上查看了一个条目,如下所示:

    Malloc 1.38 MB
    overall bytes = 1.38 MB
    #Overall = 1
    #alloc = 
    Live Bytes = 1.38 MB
    #Living = 1
    #Transitory = 0
    

    这个入口指向这个

    CGContextDrawImage(objectContext, LayerRect, objectProxy.image.CGImage); // 1
    

    如何摆脱这种内存分配释放内存?

    提前谢谢!

    2 回复  |  直到 15 年前
        1
  •  1
  •   Nicholaz    15 年前

    这张图片肯定会占用一些内存。我并不完全精通iPhone编程,但OSX下的图像总是你制作图像的副本。文档说,该图像存在于自动释放池中,因此根据您管理池的方式,它可能在那里存在相当长的一段时间。你可以试着把自动释放池放在 函数(将其放入上面引用的te函数将返回无效对象)。

    一般来说,我可以说,一旦自动释放池开始发挥作用,尝试跟踪对象的释放就会变得相当麻烦(有时甚至不可能……自动释放对象背后的想法是系统最清楚何时释放它们)(这是驱动一个C++程序员像我一样的坚果……但当然,目标C和可可不是为了让我高兴):-)

    然而,假设上面的函数名为drawOffline,您应该能够通过

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *ret= [self drawOffline];
    // do some work using ret (possibly copying it)
    [pool release];
    // memory should be released and the ret ptr is invalid from this point on.
    

    再进一步说,如果您打算使用ret ptr更长一点,您应该保留它,告诉系统即使自动释放池释放它,它也不应该删除它。

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *ret= [self drawOffline];
    [ret retain]; // prevent ret from being deleted when the pool releases it
    // do some work using ret (possibly copying it)
    [pool release];
    // ret ptr will continue to live until you release it.
    
    // more stuff
    
    [ret release]; // image behind ret being freed 
    

    如前所述,通常使用自动释放对象时,您不必担心它们的寿命,但如果您打算将它们保留更长的时间(特别是将其存储在对象成员中以供以后使用),则需要自己保留/释放它,因为否则系统可能会将其拖到您脚下。

    [1]: http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html 链接

        2
  •  -1
  •   Duck    15 年前