gpt4 book ai didi

objective-c - 强制对象在 ARC 下解除分配

转载 作者:太空狗 更新时间:2023-10-30 03:21:38 26 4
gpt4 key购买 nike

我正在开发一个 iPad 照片拼贴应用程序,它可以同时在屏幕上绘制数百个 UIImageView

有一个按钮可以让用户“重新创建”,假设对所有照片运行 for 循环到 [photo removeFromSuperview] 然后初始化一个新的批处理,按照这个顺序。

我正在使用 ARC,我的控制台告诉我我的 Photodealloc 方法在绘制下一批之后才会被调用,这意味着我遇到了内存问题,尽管我试图在添加下一组之前删除第一组。

有没有办法 1) 等到所有照片都已正确解除分配或 2) 强制所有照片在 ARC 下立即解除分配?

最佳答案

您可能在没有意识到的情况下将 ImageView 放入自动释放池中。您可以通过将您自己的自动释放池包装在您的 for 循环周围来解决这个问题。

例如,我做了一个非常简单的测试项目,在我的顶级 View 下有一个 ImageView 和一个按钮。当我点击按钮时,它会删除 ImageView 并创建一个新 View 。它通过遍历顶级 View 的 subview 来删除 ImageView 。这是代码:

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
[self initImageView];
}

- (IBAction)redoWasTapped:(id)sender {
[self destroyImageView];
[self initImageView];
}

- (void)destroyImageView {
for (UIView *subview in self.view.subviews) {
if ([subview isKindOfClass:[UIImageView class]]) {
[subview removeFromSuperview];
}
}
}

- (void)initImageView {
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"picture.jpg"]];
imageView.frame = CGRectInset(self.view.bounds, 100, 100);
[self.view addSubview:imageView];
}

@end

当我在启用“Record reference counts”的 Allocations instrument 下运行它时,我看到每个移除的 ImageView 在 destroyImageView 期间都没有被释放。相反,它稍后在运行循环调用 -[NSAutoreleasePool release] 时被释放。

然后我更改了 destroyImageView 来管理它自己的自动释放池:

- (void)destroyImageView {
@autoreleasepool {
for (UIView *subview in self.view.subviews) {
if ([subview isKindOfClass:[UIImageView class]]) {
[subview removeFromSuperview];
}
}
}
}

当我在 Instruments 下再次运行它时,我看到每个移除的 ImageView 都在 destroyImageView 期间被释放,在 @autoreleasepool block 的末尾。

关于objective-c - 强制对象在 ARC 下解除分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12827319/

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