views:

74

answers:

2

I am a C# developer getting started on Objective-C / Cocoa Touch programming. I think I might have gotten some terms wrong because I keep thinking about them "the C# way". Specifically, I have come around the term "protocol" in various documentation and tutorials.

In Objective-C, what exactly is a protocol ? Can it be compared to a C# interface ?

Is the following declaration the same as saying "The class is implementing the protocol UITextFieldDelegate" ? Or is UITextFieldDelegate to be compared with a generic type parameter in C# ?

@interface MyViewController : UIViewController <UITextFieldDelegate> { }
+2  A: 

In Objective-C a protocoll is the name for a collection of selectors/methods and is like an interface declaration in Java (probably also in C#).

@interface MyViewController : UIViewController <UITextFieldDelegate> { }

means that the class MyViewController inherits from the class UIViewController and adopts/implements the protocol UITextFieldDelegate.

This means that MyViewController must implement all methods declared in the UITextFieldDelegate.

EDIT: It seems that with the introduction of Objective-C 2.0 the possibility to mark methods of a protocol as @optional and @required was introduced. See section Optional Protocol Methods of Apples Objective-C documentation.

Helpful link from wikibooks about Objective-C Protocols.

MKroehnert
I think you are wrong about the last sentence. It _must_ not implement all the methods, but it _can_ implement them - at least that's what the docs says, and also what I am doing currently in my code.
driis
Other than that, thanks for your clear answer :-)
driis
I think something changed here with the introduction of Objective-C 2.0.But using the "old" Objective-C semantics a class must implement all methods from an adopted protocol.
MKroehnert
@driis: maybe you are talking about informal protocols here which is not the same.
MKroehnert
Well, I have declared my class with the UITextFieldDelegate protocol, but not implemented any methods yet - and the code compiles. Can methods in a protocol be optional and required ? I
driis
@driis: either the methods you don't implement are declared as `@optional` in the protocol (see my edit) or your base class already implements all methods of the protocol and you just override some of them.
MKroehnert
+1  A: 

The protocol is like an interface in some aspect. If you declare some method in protocol to be optional, the class adopt it doesn't need to implement those methods. If not, the class have to implement it.

vodkhang