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,
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?
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.
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.