01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

148 CHAPTER 7 Protocols<br />

In this animation, you take the boxView and move it down the screen by 100 pixels.<br />

Calling the commitAnimations method executes the animation. An important configuration<br />

step of this animation was setting animationWillStartSelector and<br />

animationDidStopSelector. These tell UIView to call certain classes when the animation<br />

starts and ends. These method calls are forwarded to the delegate and the protocol<br />

methods are called. The only thing left to do is create the animationStarted and<br />

animationStopped methods that alert the delegate (see the following listing).<br />

- (void)animationStarted {<br />

if ([delegate<br />

respondsToSelector:@selector(animationStartedWithView:)])<br />

{<br />

[delegate animationStartedWithView:self];<br />

}<br />

}<br />

- (void)animationStopped {<br />

if ([delegate<br />

respondsToSelector:@selector(animationHasFinishedWithView:)])<br />

{<br />

[delegate animationHasFinishedWithView:self];<br />

}<br />

}<br />

- (void)dealloc {<br />

[boxView release];<br />

[super dealloc];<br />

}<br />

@end<br />

Listing 7.4 Filling in myView.m, part 4<br />

Here is where the protocol methods are called. You tell the delegate to fire off the<br />

appropriate method when the animation has started and stopped. You don’t want to<br />

assume that a delegate is set or that the delegate has implemented the protocol methods.<br />

To check this, you use the respondsToSelector method. NSObject implements<br />

this method, so you can call it on nearly any object. It’s a great check to include in<br />

your code to avoid crashing and generally a good coding practice. If the delegate is<br />

assigned and it does implement the protocol methods, you call the method and pass it<br />

the view in which the protocols are defined. Now that you’ve defined your protocol,<br />

let’s create a class that will conform to it.<br />

7.2.2 Making a class conform to a protocol<br />

To make your application delegate conform to the animationNotification protocol,<br />

you implement both methods from the protocol in your application delegate. First<br />

you signal that the application delegate does conform to the animationNotification<br />

protocol. This is done in the myProtocolAppDelegate.h file. The following listing<br />

shows the new code for your App Delegate header file.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!