什么时候发布UIImage?

rag*_*ius 5 iphone memory-management autorelease cgimage ios

我使用以下代码绘制子图像

UIImage* subIm = getSubImage( large, rect );
[subIm drawInRect:self.bounds];
Run Code Online (Sandbox Code Playgroud)

其中getSubImage定义如下

    UIImage* getSubImage(UIImage* uim, CGRect rc){
      CGImageRef imref  = CGImageCreateWithImageInRect(uim.CGImage, rc); 
      UIImage*   sub = [UIImage imageWithCGImage:imref];
      CGImageRelease(imref);
        NSLog(@"subimage retainCount=%d", [sub  retainCount]); // is 1
      return sub;
   }//getSubImage
Run Code Online (Sandbox Code Playgroud)

代码是否正确?

"CGImageRelease"imref安全吗?

有子"CGImageRetained"imref?

我应该释放subIm(如果我这样做,我会收到错误)吗?

subIm是否包含在自动释放池中,如果是,我怎么知道这个?

通常,可以检查自动释放池中是否包含对象(用于调试目的)?

bbu*_*bum 15

不要叫-retainCount

保留计数返回的数字是对象的绝对保留计数.由于它们是框架的实现细节,因此可能存在许多无法控制的保留.有总是更好的方法来验证你的代码的内存管理.

保留计数应仅视为增量; 如果您导致保留计数增加,则必须使其减少.

鉴于:

UIImage* getSubImage(UIImage* uim, CGRect rc){
  CGImageRef imref  = CGImageCreateWithImageInRect(uim.CGImage, rc); 
  UIImage*   sub = [UIImage imageWithCGImage:imref];
  CGImageRelease(imref);
    NSLog(@"subimage retainCount=%d", [sub  retainCount]); // is 1
  return sub;
}//getSubImage
Run Code Online (Sandbox Code Playgroud)

imageWithCGImage:返回一个自动释放的对象.保留计数无关紧要,因为imageWithCGImage:内部可能会执行任何可能影响保留计数的事情 - 缓存等.

get*是一个奇怪的模式在Cocoa编程中使用.你只是看不到那么多.

我建议像:

- (UIImage *) subImage: (UIImage *) anImage inRect: (CGRect) aRect
{
      CGImageRef imageRef  = CGImageCreateWithImageInRect(anImage.CGImage, aRect); 
      UIImage*   subImage = [UIImage imageWithCGImage: imageRef];
      CGImageRelease(imageRef);
      return subImage;
}
Run Code Online (Sandbox Code Playgroud)


Eon*_*nil 6

内存管理有一个命名约定.所有 Cocoa代码都遵循以下规则:

基本内存管理规则

我强烈建议您阅读本文档并遵守规则.命名规则也是Cocoa的一部分.

从参考文档:

您拥有自己创建的任何对象.使用名称以"alloc"或"new"开头或包含"copy"(例如,alloc,newObject或mutableCopy)的方法"创建"对象.

完成后,您必须放弃您拥有的对象的所有权.您通过向对象发送释放消息或自动释放消息来放弃对象的所有权(自动释放在"自动释放"中有更详细的讨论).因此,在Cocoa术语中,放弃对象的所有权通常被称为"释放"对象.

Core Foundation框架的C函数有类似的规则.然而,没有像自动释放这样的东西.如果要使用C函数制作Objective-C对象,则必须澄清文档中的所有内容.

这可能对你有所帮助: imageWithCGImage和memory


Vde*_*edT 4

SubIm 已注册到 AutoRelease Pool 中,因为该对象实际上是由类方法 imageWithCGImage 创建的,并且规则是由类方法创建的实例应始终返回自动释放的实例。

代码是正确的,但我不明白为什么你使用 C 语法而不是 Obj-C 语法来定义你的函数