我是iPhone/iPad編程的新手。我有一個for循環的問題,就像我在這個例子中使用的那個。該程序的工作原理應該如此。只有在每次調用函數後(在本例中爲 - (void)writeLabels),它纔會變得越來越慢。誰能告訴我爲什麼?在此示例中,需要50到100次點擊才能注意到延遲。但是,一旦我在循環中包含更多指令,程序就會變得太慢,因此只有在幾次點擊後纔會無法使用。另外一個autorelease池並沒有幫助。目標c:for循環變得越來越慢
- (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];
}
完全正確,但我認爲使用標籤識別和定位視圖是一種醜陋而脆弱的解決方案。我建議保留對視圖的實際引用。 – Jonah 2011-05-14 16:49:23
非常感謝,這很有道理。但是,因爲我是新的:代碼將如何看起來像? – 2011-05-15 10:57:18
@Andrew,請檢查編輯。希望能幫助到你。 – taskinoor 2011-05-15 12:36:34