Objective C protocols usage

TeaCupApp picture TeaCupApp · Oct 1, 2011 · Viewed 8.4k times · Source

I have a homework question which confused me, really badly. Below is a brief explanation of a question.

Imagine you are developing an application that stores contact information. The address book may contain many entity types e.g. Human being, a company or anything else that has a contact information.

  • Now instead of explicitly checking every object type write a protocol that declares how an object must behave and successfully appear in your address book.

My understanding and efforts of answering this question is,

  1. Build a protocol which has common methods of each type of contact information under @required tag. And all other methods which are not similar in different contact(Such as fax number has association with company but not person...) under @optional. At runtime you can check whether an object responds to any given method by using selector. Doubt : However this is again explicitly checking object type indirectly, am I right?

  2. My second thought is to use something like abstract class in java. Which means inherited class's from abstract class implements their own abstract methods. How ever as a naive iOS developer I don't know how to implement this? and I am not sure whether this is going to solve my problem. I would like get enlighten if someone knows this.


External Reading done so far, Please let me know if the answer I am looking for is in one of these links. I will read it again to understand and solve this :). thanks.

  1. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF144

  2. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF146

  3. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF149

Answer

Matt Williamson picture Matt Williamson · Oct 1, 2011

A protocol is the same thing as a Java interface. It just defines which methods the class should support. Here's a page that explains it clearly: http://www.otierney.net/objective-c.html#protocols

Essentially if you want to make sure a class will have a phoneNumber method (accessor to the phoneNumber property) you would do something like this:

@protocol ContactProtocol
-(void) phoneNumber;
@end

@interface Person: NSObject <ContactProtocol> {
    ...
}

@interface Company: NSObject <ContactProtocol> {
    ...
}

And then at compile time (or live for xcode 4) it will tell you if you forgot to add the phoneNumber method to the Person or Company classes.