What is the meaning of protocols?

I write various materials using protocols, as an example of code, but I also use some third-party things, and they seem to take completely different approaches. Some specifically use protocols in the interface, using

@interface myClass <myProtocol> 

others do not do this at all and simply pass themselves on and then set themselves up as delegates, but the end result seems to be exactly the same. I tried both and they both work great. If anyone could explain this, I would be a happy tourist! Thank you very much.

+3
objective-c protocols delegates
May 04 '11 at 9:16
source share
3 answers

The protocol declares a set of messages to which the object should respond (or @optional , may respond to). In Objective-C, its only (almost) * point is to allow the compiler to flag warnings if you pass an object that does not implement all protocol methods with the correct signatures.

Taking a simple example: NSMutalbeDictionary has a method - setObject: ForKey:, which sets a value for a specific key. The key is declared as an id type, which means that you can pass any object, and the compiler will not complain. However, the method documentation states:

The key is copied (using the copyWithZone :; keys must comply with the NSCopying protocol).

therefore, if you pass an object that does not have the -copyWithZone: method, at run time you will get an exception saying that the key does not respond to -copyWithZone: It would be nice if the compiler could detect your error.

If Apple announced a method

 -(void)setObject:(id)anObject forKey:(id<NSCopying>)aKey; 

the compiler would know about the requirement -copyWithZone: (this is the only method declared by NSCopying ) and catch any instances of passing incompatible objects at compile time. I think the reason they did not do this is backward compatibility. If bbum is reading, he may know the true reason, why not.




* I say "almost" because you can check if the object matches the protocol at startup time.

+4
May 04 '11 at 9:50
source share

Objective-C can perform both static and dynamic typing, so the arent protocol is really required for common use cases. You can always enter the delegate as id and then send it no matter what you want. (The compiler will warn you if you try to send a message that is not visible from the current file. This is the only health check that it can do for id objects that do not perform extended type inference.)

But narrowing the type of id down by protocols is nice and recommended, because 1) the code is more readable, 2) the compiler will warn you if you try to send a fictitious message to the delegate, and 3) you get better at code completion.

+1
May 4 '11 at 9:34
source share

Also, Xcode Code Sense can be very useful if you use protocols. Sometimes he suggests missing methods.

+1
May 4 '11 at 10:17
source share



All Articles