01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

150 CHAPTER 7 Protocols<br />

The first thing this code does is fill in the applicationDidFinishLaunching method,<br />

which is part of the UIApplicationDelegate protocol. In here you create a button<br />

that calls another method you’ll define. You create the myView object and set the<br />

myView delegate to this class B. Then you add the view into your window. Next you<br />

make a button in code c. This is the button you’ll tap to call the animate method in<br />

myView d. With this done, you must make a method that tells myView to animate<br />

when the button is pressed. The code is short—check it out; this should be added as a<br />

method to myProtocolAppDelegate.m:<br />

- (void)animate {<br />

[view animate];<br />

}<br />

This code calls the animate method in myView. All that’s left to do is define the protocol<br />

methods and implement what you want them to do. For this example, two things<br />

happen when the animation starts, as shown in the following listing.<br />

Listing 7.7 Filling in myProtocolAppDelegate.m, part 2<br />

- (void)animationStartedWithView:(UIView*)animatedView {<br />

NSLog(@"The animation has started");<br />

[animatedView setBackgroundColor:[UIColor whiteColor]];<br />

}<br />

Fire up the simulator and see this in action. If your terminal is up, you can see the log<br />

messages as well. You’ve successfully defined and implemented a custom protocol.<br />

7.3 Important protocols<br />

Now that you’ve seen all the guts of making and implementing a protocol, let’s look at<br />

the most popular protocols used in the development of an iPhone application. Apple<br />

relies on the protocol design method for many of its Cocoa classes. In this section we<br />

review four sets of protocols that you’ll likely use when developing your application.<br />

Let’s dive in.<br />

7.3.1 <br />

Write a log<br />

message<br />

Set background to white<br />

- (void)animationHasFinishedWithView:(UIView*)animatedView {<br />

NSLog(@"The animation has finished");<br />

Write a log message<br />

[animatedView setBackgroundColor:[UIColor blackColor]];<br />

}<br />

Set background<br />

- (void)dealloc {<br />

to black<br />

[view release];<br />

[window release];<br />

[super dealloc];<br />

}<br />

@end<br />

The UITableViewDataSource protocol is a mandatory protocol to have implemented<br />

for any table view in your application. A table view is a visual element that’s meant to<br />

display some collection of information. Unlike any other user interface element in the

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

Saved successfully!

Ooh no, something went wrong!