gpt4 book ai didi

iOS 在带有 ARC 的 MutableArray 中保存 UIView 引用

转载 作者:行者123 更新时间:2023-11-28 22:26:32 25 4
gpt4 key购买 nike

我尝试管理多个 View 并将这些引用保存在一个可变数组中。如果我既在可变数组中添加 View 引用,又作为 subview 添加到 View 中。然后引用计数似乎不正确。会导致bad access错误。

所以我的问题是,是否有管理这些 View 的好方法。例如,如果我需要重用 View 。在不使用时将它们保存在一个可变数组中,并在以后重用它们。

编辑:

    NSMutableArray* reuseViews = [NSMutableArray arrayWithCapacity:0];
for (int i=0; i<3; i++) {
UIView* v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[reuseViews addObject:v];
[self.view addSubview:v];
}

for (int i=0; i<3; i++) {
UIView* v = [reuseViews objectAtIndex:i];
[v removeFromSuperview]; // it also removes the reference in the array
[reuseViews removeObject:v]; // will crash
}

最佳答案

第二个 for 循环在尝试删除第三个项目时会崩溃。这是因为 i 的值为 2,索引中的项目数为 1。当您尝试将对象从数组中拉出时,它会崩溃。

要解决此问题,请等到循环结束后删除所有对象:

for (int i=0; i<3; i++) {
UIView* v = [reuseViews objectAtIndex:i];
[v removeFromSuperview];
}

[reuseViews removeAllObjects];

更好的方法是使用快速枚举:

 for (UIView* v in reuseViews) {
[v removeFromSuperview];
}

[reuseViews removeAllObjects];

关于iOS 在带有 ARC 的 MutableArray 中保存 UIView 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802577/

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