【问题标题】:Memory handling on re-assignment重新分配时的内存处理
【发布时间】:2011-03-11 15:36:23
【问题描述】:

内存管理是如何工作的?重新分配给另一个图像的 UIImage。

例如

someImage = image1.png

someImage = image2.png

image1.png 在内存方面会发生什么变化?重新分配是否会泄漏?

图片将从文档目录加载。

【问题讨论】:

  • 你问的方式让人很难理解你真正想知道什么。这是代码吗?还是伪代码?图片不能分配给图片。

标签: iphone objective-c memory-leaks


【解决方案1】:

这取决于您如何加载图像。就像任何其他对象一样,如果你自己分配和初始化,那么你必须清理自己。否则,您可以依赖自动释放的对象。

这不会泄漏:

UIImage* someImage;
someImage = [UIImage imageWithContentsOfFile:@"<path>/file1.png"];
// usage the image here ...
someImage = [UIImage imageWithContentsOfFile:@"<path>/file2.png"];
// use the image again ...

这将:

UIImage* someImage;
someImage = [[UIImage alloc] initWithContentsOfFile:@"<path>/file1.png"];
// usage the image here …
someImage = [[UIImage alloc] initWithContentsOfFile:@"<path>/file2.png"];
// use the image again ...

只要您坚持使用 Cocoa 类,它就真的很简单 - 而且您可能不再需要徘徊在 Carbon API 中。 :)

【讨论】:

    【解决方案2】:

    这取决于您如何分配图像。

    如果你这样做

    UIImage *someImage = [[UIImage alloc] initWithContentsOfFile:@"image1.png"];
    ...
    someImage = [[UIImage alloc] initWithContentsOfFile:@"image2.png"];
    

    将会发生内存泄漏,因为您拥有someImage 的所有权并且您没有释放它。

    正确的做法是:

    UIImage *someImage = [[UIImage alloc] initWithContentsOfFile:@"image1.png"];
    ...
    [someImage release];
    someImage = [[UIImage alloc] initWithContentsOfFile:@"image2.png"];
    ...
    [someImage release];
    

    或者你可以使用自动释放的对象

    UIImage *someImage = [[[UIImage alloc] initWithContentsOfFile:@"image1.png"] autorelease];
    ...
    someImage = [[[UIImage alloc] initWithContentsOfFile:@"image2.png"] autorelease];
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用带有“保留”属性集的@property(与@synthesize 一起使用)。但是,当您分配它们时,您需要“释放”分配的对象:

      @property (retain) UIImage *someImage;
      ...
      @synthesize someImage;
      ...
      self.someImage = givenImageg1;
      ...
      self.someImage = givenImage2;
      

      最后一行将释放第一个图像集,然后保留第二个图像集。请注意,您必须使用“自我”。为了确保你使用了 setter 方法,否则什么都不会发生。

      【讨论】:

        猜你喜欢
        • 2017-04-03
        • 2010-12-31
        • 2015-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        相关资源
        最近更新 更多