开发者

Why use an Objective-C protocol when all methods are optional?

开发者 https://www.devze.com 2023-03-17 12:52 出处:网络
I always had the impression a protocol should help me implement certain methods so my object will responds to certain messages. If I forget a method or type it wrong the compiler will tell me.

I always had the impression a protocol should help me implement certain methods so my object will responds to certain messages. If I forget a method or type it wrong the compiler will tell me.

But what i开发者_StackOverflows the use of setting a protocol for a class when all methods are optional? Like in the NSSpeechSynthesizerDelegate-protocol. The compiler doesn't remind me to implement some methods and he doesn't tell me if I wrote a method name the wrong way. And the program works fine even without the protocol.


If you implement a delegate protocol of your own, you will get compiler warnings if you try to call the methods without them being declared somewhere (x may not respond to selector...).

It also helps with documentation and code completion to define a protocol. If you want to know which delegate methods are supported, you can simply look at the corresponding header file (or a documentation page that is generated from it).

When you start typing a new method in your class, Xcode is also smart enough to suggest method signatures from protocols your class conforms to.


You can omit a protocol with all optional methods, and if you don't need them at all. Doc says,

However, an Objective-C program doesn’t need to use protocols. Unlike class definitions and message expressions, they’re optional. Some Cocoa frameworks use them; some don’t. It all depends on the task at hand.

If you don't want the help of such protocols, you can simply omit it.


because your program is not necessarily interested in all, but some. the important part for your implementation is which.


In OOP is common to program by interface (in objective c protocols are interfaces) not implementation, because this is a flexible and powerful way of implementing a solid software architecture, in which you don't have to care about how a class is implemented but only that it match a certain interface. (a search on google about the argument: http://www.google.com/search?hl=en&source=hp&biw=1436&bih=768&q=program+by+interface+not+by+implementation&oq=program+by+inter&aq=2j&aqi=g-j2&aql=&gs_sm=e&gs_upl=849l7924l0l10059l20l16l2l3l3l0l283l1295l7.3.1l11l0)

0

精彩评论

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