May 2008 Archives

This is another article aimed at the Java programmer.  This will touch very very briefly on protocols.

Protocols are Objective C's version of what is known in Java as "interfaces". 

Defining the protocol

To make one, first create a blank .h header file.
Then type:

@protocol MyProtocolName <NSObject>
//Method declarations go here

Replace "MyProtocolName" with the name of your choice.

You will notice a couple of things...first, there are no curly brackets.  That's because variables go in curly brackets, and protocols have no variables associated with them.

Second, notice the "<NSObject>".  This actually means that the current protocol is a derivative of the NSObject protocol.  (There is both an NSObject class and an NSObject protocol...this is the protocol...)

In objective C, you have protocols and categories.  Pointed brackets are associated with protocols.  Curved brackets (aka parentheses) are associated with categories.   So just remember, "pointy protocol, curved category"...

Using the protocol

In Java, you specify that a class implements an interface with the "implements" keyword.  In Objective C, you use the pointy brackets in the interface declaration (and by "interface" here, I mean the part of the class in the header file, not "interface" in the Java sense), following the class you extend. For example, suppose your class was normally declared like:
@interface CustomView : UIView

To specify that it implements a protocol, simply change it to this:

@interface CustomView : UIView <MyProtocolName>

Protocols as variables

Here is where it differs from Java the most.  In Java, when declaring a variable, you would use an interface name just like you would a class.  In Objective C, you declare a variable this way:

id<MyProtocolName> myNewVariable;

So the new type is "id<MyProtocolName>".  "id" is the generic object...even though it is a pointer to an object, it doesn't have an asterisk...that's assumed.

You can also use this notation when defining a method...e.g.

- (void) doSomethingWithThisObject: (id<MyProtocolName>) aObject

There's a lot more to protocols than what I've mentioned, but this should be enough to get you started.

About this Archive

This page is an archive of entries from May 2008 listed from newest to oldest.

April 2008 is the previous archive.

Find recent content on the main index or look in the archives to find all content.



Powered by Movable Type 4.1-en-release-26-r1120-20071224