gpt4 book ai didi

iPhone 内存管理和释放

转载 作者:太空狗 更新时间:2023-10-30 03:42:37 25 4
gpt4 key购买 nike

这是我经常看到的常见做法(包括来自一本非常受欢迎的 iPhone 开发人员书籍)

在.h文件中:

@interface SomeViewController : UIViewController
{
UIImageView *imgView;
}

.m 文件中的某处:

imgView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]
applicationFrame]];
[imgView setImage:[UIImage imageNamed:@"someimage.png"]];
[self addSubview:imgView];
[imgView release];

后来,我们看到了这个......

- (void) dealloc
{
[imgView release];
[super dealloc];

}

既然imgView有配套的alloc和release,那么dealloc中imgView的release是否有必要呢?

addSubview 调用保留的 imgView 在哪里?

最佳答案

代码不正确。您最终会在释放 imgView 后释放它。

在您的 .m 文件中,您:

  1. alloc 它 --> 你拥有它
  2. 将其添加为 subview --> 你和 the UIView owns it
  3. 发布它 --> 你不拥有它

然后在 dealloc 中,您释放 imgView,尽管正如我们在上面的第 3 步中确定的那样,您并不拥有它。当您调用 [super dealloc] 时, View 将释放其所有 subview ,我想您会得到一个异常。

如果你想保留 imgView 的 ivar,我建议 不要 在将它添加为 subview 后调用 release,并保留你的dealloc 同理。这样,即使 imgView 在某个时候从 View 层次结构中删除,您仍将拥有对它的有效引用。

关于iPhone 内存管理和释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/822982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com