I am a beginner to programming, and a beginner to Objective-C. I learned basic C and decided to start learning Objective-C. I am reading \"Programming in Objective C 2.0\" b
Like @conmulligan says Objective-C uses protocols to make classes talk to each other.
Its one of many ways to communicate between classes.
But protocols is necessarily a bad way.
I use protocols if I was to create a re-usable object, that is usually used for many projects.
So I create protocols to make my code easy to maintain.
If you've done any kind of object-oriented programming, you probably know protocols as interfaces (they're not identical, but the concept is similar). If not, think of protocols as blueprints.
The main reason why you'd use protocols is so you can use objects without knowing everything about them; all you need to know is that they implement a set of methods. For example, if the classes Business
and Person
conform to the protocol Contact
, which defines the method - (NSString *)phoneNumber
, the class AddressBook
can call -(NSString *)phoneNumber
without knowing whether or not the object is of type Business
or Person
.
Once you start to learn about Cocoa and delegates, you'll see how powerful and important protocols are.
One word, delegates.
Objective-c uses delegates all over the place to allow classes to talk to each other.
To see an example see UITableViewDelegate Protocol
That's not the only place @protocol
is used, but it's probably the most common use for it.
Protocols are better versions of callback functions in C. Protocols are useful constructs when you want to implement MVC architecture yourself. The Views need to be notified when Model changes,You can use protocols to notify appropriate events to Observers.
You could have a class that is a UIViewController, and it implements several protocols, such as UITableViewDelegate, UITableViewDataSource. A class can do more than one thing.