A Brief Intro to Objective C Protocols

| | Comments (0) | TrackBacks (0)
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
@end

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.














0 TrackBacks

Listed below are links to blogs that reference this entry: A Brief Intro to Objective C Protocols.

TrackBack URL for this entry: http://mauvilasoftware.com/cgi-bin/mt/mt-tb.cgi/30

Leave a comment

About this Entry

This page contains a single entry by JLA published on May 12, 2008 10:36 AM.

iPhone Low Level Audio Part II : AudioQueue Output was the previous entry in this blog.

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

Categories

Pages

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