gpt4 book ai didi

iphone - objective-c : for-loop gets slower and slower

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

我对 iPhone/iPad 编程还很陌生。我对 for 循环有疑问,就像我在本例中使用的那样。该程序可以正常工作。只是,在每次调用该函数(在本例中为 (void) writeLabels)之后,它变得越来越慢。谁能告诉我为什么?在此示例中,需要点击 50 到 100 次才能注意到延迟。但是,一旦我将更多指令打包到循环中,程序就会变得太慢,因此只能在单击几下后无法使用。自动释放池也无济于事。

- (void) writeLabels {

label_y = 0;

for (i = 0; i < 23; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i * i, label_y, 39, 39)];
label.textColor = [UIColor whiteColor];

if (offset == i) {
label.backgroundColor = [UIColor blackColor];
}
else label.backgroundColor = [UIColor blueColor];

[label setText:[NSString stringWithFormat:@"%d", i]];
[self.view addSubview:label];

[label release];
label_y += 40;
}
}
- (IBAction) pushPlus {

++offset;
if (offset == 23) offset = 0;
[self writeLabels];

}

最佳答案

writeLabels 方法中,您将标签添加为 subview 。但是您从未删除以前的标签。所以在第一次调用之后你有 24 个标签 subview ,在第二次调用之后你有 48 个等等。每次调用都会增加内存消耗,程序会变慢,最终可能会崩溃,尽管这里没有内存泄漏。这不是泄漏,但是您在内存中保留了不必要的东西。我想对于第二次、第三次……调用之前的标签是不必要的,毕竟你在每次调用中都在相同的位置创建它们。保留一种方法来跟踪添加的标签(可能是通过使用标签),并在添加新标签之前从 super View 中删除以前的标签。

编辑:最好按照 Jonah 的建议将标签作为类(class)成员。像这样:

- (id)init {
if (self = [super init]) {
// labelsArray is a member of the class
labelsArray = [[NSMutableArray alloc] initWithCapacity:24];
NSInteger label_y = 0;

for (NSInteger i = 0; i < 23; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i * i, label_y, 39, 39)];
[labelsArray addObject:label];
[label release];
label_y += 40;
}
}
}

- (void)viewDidLoad {
for (NSInteger i = 0; i < 23; i++) {
UILabel *label = (UILabel *) [labelsArray objectAtIdex:i];
[self.view addSubview:label];
label.text = [NSString stringWithFormat:@"%d", i];
}
}

- (void) dealloc {
[labelsArray release];
}

- (void) writeLabels {
for (NSInteger i = 0; i < 23; i++) {
if (offset == i) {
label.backgroundColor = [UIColor blackColor];
} else {
label.backgroundColor = [UIColor blueColor];
}
}

关于iphone - objective-c : for-loop gets slower and slower,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6003203/

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