Monday, July 26, 2010

iPhone : Protocols

Pointy protocol, curved category
In objective C, Pointed brackets are associated with protocols. Curved brackets are associated with categories.

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

Defining the protocol

@protocol MyProtocolName
//Method declarations go here
@end

there are no curly brackets. That's because variables go in curly brackets, and protocols have no variables associated with them.

Notice '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...)

The concept of protocols: Protocols are a strange & interesting cross between interfaces and event definitions. In the languages (C#, VB.NET, Java etc… ) when you define an interface, you’re defining a common set of methods that objects must implement if they want to be considered to “implement” a given interface. One of the requirements of implementing an interface is that you must implement every method in the interface, either directly or via a subclass by marking the method as abstract.
Interfaces are use frequently for implementing “event callbacks”.

We basically define a standard set of methods/events, called a protocol, that our class will call. Then, when instances of our class are created, a class implementing our protocol, called a ‘delegate’, can register itself as a handler. Take the following protocol definition below:

@protocol MyProtocolDefinition
@required
- (void) Save:(NSString*) stringToSave;
@optional
- (void) OptionalMethod:(NSString*) parameter;
@end

The above code indicates that the Save() method is a required method to implement in classes implementing this protocol. However, the OptionalMethod is optional, meaning classes wanting to use this protocol only need to implement the Save() method, but they could also implement the OptionalMethod.

Using the protocol

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, following the class you extend.
For example, suppose your class was normally declared like:
@interface myClass : UIView

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

@interface myClass : UIView


Protocols [As variables]

In Objective C, you declare a variable this way:

id myNewVariable;

So the new type is "id". "id" is the generic object.

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

- (void) doSomethingWithThisObject: (id) aObject

Enjoy Coding passionately :)

No comments:

Post a Comment