Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the "forKey" parameter when adding a CAAnimation to a layer?

I am very new to iOS programming, Objective-C, and programming in general, so please excuse me if you find this question frustratingly simple-minded.

The docs on Apple's website are usually great, but I'm having some trouble trying to wrap my head around certain parts of Core Animation. I want to explicitly animate the position of a CALayer. From what I understand, I need to create a CABasicAnimation object, configure it with fromValue, toValue, etc., then add it to a layer using this method:

- (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key

My problem is that I have no idea what the significance of the forKey: parameter is. From what I've seen in examples online, it's not required? I suppose it has something to do with key-value coding? (I still don't really understand that, either.) Even if it's not required, I'd like to know what it is so that I can take advantage of its usefulness in my app.

Thanks for any help you can offer.

like image 738
Andrew Clark Avatar asked Dec 06 '11 21:12

Andrew Clark


2 Answers

It allows you to override animations. For example, implicit animations created by mutating an implicitly animateable property (such as opacity) will use the name of the property as a key. This way if you modify it again (to produce a new animation), the new animation will replace the old one instead of trying to have both animations running simultaneously.

like image 143
Lily Ballard Avatar answered Oct 15 '22 13:10

Lily Ballard


CALayer has several methods for getting the animations that have been added to the layer. If you want to get, replace, or remove a particular animation from CALayer you have to give it the key when you call animationForKey: or removeAnimationForKey:.

You don't have to provide a key, you can use nil for the key if you don't have any particular need to find a particular animation by key.

like image 21
progrmr Avatar answered Oct 15 '22 13:10

progrmr