Suppose I have the following code running. I’m dynamically creating 1000 UILabels added to a UIScrollview. However this code runs incredibly slow because I have to create a new UILabel every time the loop comes around. I can’t move the line UILabel *dayLabel = [[UILabel alloc] init]; before the loop because then it only creates 1 UILabel. Any thoughts on how I can optimize this piece of code?
for (int i=0; i<1000; i++) {
UILabel *dayLabel = [[UILabel alloc] init];
dayLabel.multipleTouchEnabled = YES;
dayLabel.frame = CGRectMake(0, 40 * i, 40, 40);
[_scroller addSubview:dayLabel];
}
The only way around the problem of creating objects is to not create them. Or at least not create them yet.
All 1000 labels are not going to fit on the screen, so you need to create only a group of labels that fit. Then you watch for the scroll events, and create dynamically the labels that become visible. At the same time, you remove labels as they get scrolled off the screen. Keep these labels around: rather than creating a new one each time, you can reuse an old one from the recycled list.
By now you are probably wondering if you had seen this scheme somewhere. You are right, it is the same scheme that UITableView uses for its cells. It is a complex piece of code, so if you could replace a scroll view full of labels with a table, you would save yourself a lot of work.