I am doing some testing to try to come up with the best way to add small animations to a UIImageView.
The following code is working however when called for the first time there is a delay where I am guessing the animation is loading. How should I load the animation to avoid this delay? When called for a second time it starts instantly. This code is in the -(void)loadView method and [animation startAnimating]; is called from a custom method. Note: UIImageView *animation is actually a instance var.
NSString *imageName;
NSMutableArray *animImages = [[NSMutableArray alloc]init];
for(int i = 0; i <= 40; i++) {
imageName = [NSString stringWithFormat:@"frame_%d.png", i];
[animImages addObject:[UIImage imageNamed:imageName]];
}
UIImageView *animation; // is actually an instant var declared in header.
animation = [[UIImageView alloc]initWithFrame:CGRectMake(50, 0, 600, 300)];
animation.animationImages = animImages;
animation.animationDuration = 2;
animation.animationRepeatCount = 1;
I need to have several animations on the same UIView so I would also like to know if this is the best way to add multiple animations on a view and the correct way to manage the memory in this method.
Many thanks
Prefer to load resources in viewDidLoad and not loadView. You should trash them in viewDidUnload, loading in viewDidLoad will get them back should your view load again.
One could argue that you could also trash them in didReceiveMemoryWarning, but AFAIK viewDidUnload should be used to release UI elements. If you use didReceiveMemoryWarning you can check if viewDidLoad will be called again by releasing only if viewDidUnload got called:
But if animation is the instance var and you are really doing this
you are not setting the intance variable but a local.
Later
As to the delay: loading 40 images needs its time no matter what you do. If you don’t want the delay in the UI load them in the background and notify UI when it is done. In this time you can show something that draws the attentions off the delay.