【问题标题】:Assigning objects in Objective-C, memory management在 Objective-C 中分配对象,内存管理
【发布时间】:2011-07-22 20:55:14
【问题描述】:

我有一个关于在 Objective-c 中分配对象的超级菜鸟问题。我基本上是在尝试创建一组要使用的缩略图。我有这个代码来自另一个帖子。

+ (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

在我的 viewDidLoad 中,我这样做:

// Create thumbnail images to be used in UITableView.
    NSMutableArray *imageArray = [[NSMutableArray alloc] initWithCapacity:[_list count]];  // list is an array that has my data
    for (id *test in _list) {
        UIImage *cardImage = [UIImage imageNamed:test.ImageFile];  // line 1
        cardImage = [UIImage scale:cardImage toSize:CGSizeMake(50, 50)];  // line 2
        [imageArray addObject:cardImage];  // line 3
    }
    self.List = imageArray;
    [imageArray release];

我的问题是关于 for 循环内部的。这是我对它的工作原理的理解,如果我错了,请纠正我。

第 1 行创建一个名为 cardImage 的自动释放 UIImage。

第 2 行从 scale:toSize: 方法创建另一个 UIImage。 (我不确定这个 UIImage 是否是自动发布的)。 cardImage 现在指向在第 2 行创建的新 UIImage,并且稍后将清理第 1 行中自动释放的 UIImage。

第 3 行将该新对象添加到 imageArray。

我不确定这是对/错/好/坏等。我知道在方法中使用原始类型,您可以这样做

int x = 5;
x = 10;

但我不确定这样做是否会造成内存泄漏,以及是否有更好的方法。非常感谢!

【问题讨论】:

    标签: iphone objective-c memory-management


    【解决方案1】:
    + (UIImage *)scale:(UIImage *)image toSize:(CGSize)size
    {
        ...
        UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        ...
        return scaledImage;
    }
    

    UIGraphicsGetImageFromCurrentImageContext 返回一个自动发布的图像,scale:toSize: 也是如此。因此,您的循环不会泄漏。

    你的第一个线索可能是名字:scale:toSize:。根据Memory Management Rules,只有名称以“alloc”、“new”、“copy”或“mutableCopy”开头的方法才会返回您拥有的对象。其他方法返回不属于您的对象。

    【讨论】:

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