【问题标题】:Memory issue after releasing the object释放对象后的内存问题
【发布时间】:2011-10-19 11:43:47
【问题描述】:
NSArray *imageExtension  = [info.ThemeImage componentsSeparatedByString:@"."];
NSString *path = [[NSBundle mainBundle] pathForResource:[imageExtension objectAtIndex:0]ofType:@"png"];
UIImage *image = [[UIImage alloc]initWithContentsOfFile:path];
image=[image addImageReflection:0.50];

[CarouselView  setFrame:CGRectMake(0,-200, image.size.width, image.size.height)];

UIButton *button = [[UIButton alloc]init];
[button setFrame:CGRectMake(0,0, image.size.width, image.size.height)];

[button setBackgroundImage:image forState:UIControlStateNormal];
[image release]; 

释放对象图像后,我确实有内存泄漏......

我不知道为什么它在仪器泄漏中显示内存泄漏

【问题讨论】:

  • addImageReflection 是否正在创建第二个图像对象?

标签: ios cocoa-touch memory-management


【解决方案1】:

上面的代码存在三个问题会导致内存泄漏。

首先,您在此处创建image

UIImage *image = [[UIImage alloc]initWithContentsOfFile:path];

然后您将指针image分配给其他东西,从而丢失原始引用:

image=[image addImageReflection:0.50];

addImageReflection 我假设给你一个自动释放的对象。

尽管如此,你稍后发布image

[image release]; 

你在这里释放的不是你分配的原始指针,而是后来分配的自动释放对象。因此,过度释放会造成第二个问题。

最后,您还有第三个问题。您在此处创建的 objectbutton 永远不会被释放:

UIButton *button = [[UIButton alloc]init];

【讨论】:

    【解决方案2】:

    你没有松开按钮?如果上面的代码在一个函数中并且被多次调用,按钮就会泄漏。 尝试添加

    [button release];
    

    【讨论】:

      【解决方案3】:

      做完之后还是一样吗?

      [[self view] addSubview:button];
      [button release];
      

      【讨论】:

        【解决方案4】:

        在这里你正在分配一个新的 UIImage

        UIImage *image = [[UIImage alloc]initWithContentsOfFile:path];
        

        在这里,您正在对图像执行一些操作(反射?),并且可能此函数返回一个自动释放的实例。在这里,您正在将该实例重新分配给您的原始实例变量。您将失去对原始图像实例的引用,它会被泄露..你也引用了一个自动释放的实例

        image=[image addImageReflection:0.50];
        

        之后你错误地尝试释放,这将导致崩溃..

        [image release];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多