开发者

What exactly does "adopt a protocol" mean in the Objective-C / Cocoa documentation?

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 va开发者_如何学JAVArious 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> { }


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜