What is a Protocol? - objective-c

I've read the documentation but I'm still confused. Can someone please explain what a protocol is? (You could give code examples but I'm really looking for an explanation)

Here's a great article on it. Effectively, a protocol in Objective-C is very similar to an interface in Java or a pure virtual class in C++ (although not exactly as pure virtual classes can have data members...). It's basically a guarantee that a specific class knows how to respond to a given set of methods (messages).
Edit The original article disappeared so I have replaced it with a different tutorial.

A protocol is means to define a list of required and/or optional methods that a class implements. If a class adopts a protocol, it must implement all required methods in the protocols it adopts.
Cocoa uses protocols to support interprocess communication through Objective-C messages. In addition, since Objective-C does not support multiple inheritance, you can achieve similar functionality with protocols, as a class can adopt more than one protocol.
A good example of a protocol is NSCoding, which has two required methods that a class must implement. This protocol is used to enable classes to be encoded and decoded, that is, archiving of objects by writing to permanent storage.
#protocol NSCoding
-(void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;
#end
To adopt a protocol, enclose the name of the protocol in <> like below
#interface SomeClass : NSObject <NSCoding>
{
some variables
}
How to define a Protocol?
We can create both required an optional methods within a protocol. What follows is a definion of a protocol named 'Hello':
#protocol Hello
- (BOOL)send:(id)data;
- (id)received;
#optional
- (int)progress;
#end
To use the protocol, as with the example above, declare the protocol in the interface and write the required methods in the class implementation:
// Interface
#interface AnotherClass : NSObject
{
some declaration
}
// Implementation
#implementation AnotherClass
- (BOOL)send:(id)data
{
some declaration
}
- (id)received
{
some code
}
// Optional method
- (int)progress
{
some code
}
#end
I hope it helps you to learn Protocol.

Related

Implement protocol through methods declared in superclass?

I'm wondering if it is possible, in a certain subclass, to "recognise" methods declared in it's superclass as implementations of methods declared in a protocol the subclass adheres to, given that they have the same signatures.
It kind of gets hard to even formulate this, that's why any searches I made turned out fruitless so far.
But let me make the case with an example for better understanding.
Protocol:
#protocol TheProtocol <NSObject>
- (void)theProtocolMethod;
#end
Superclass:
// Superclass does not adhere to TheProtocol
#interface TheSuperClass : NSObject
- (void)theProtocolMethod;
#end
#implementation TheSuperClass
- (void)theProtocolMethod
{
// stuff
}
#end
Subclass:
// SubClass adheres to TheProtocol but does not implement it's methods
// since they are implemented in the class it is subclassing. Is this OK?
#interface TheSubClass : TheSuperClass <TheProtocol>
#end
#implementation TheSubClass
#end
Is this anywhere close to being "OK"?
What about the case TheSubClass was in fact a category of TheSuperClass (declaring adherence to TheProtocol) and not a subclass?
A bit more context:
It's a scenario involving Core Data. I need to publish an accessor defined in an Entity Class, in a Protocol that will be used in a separate Framework for developing plugins for my app. The Protocol itself is fully implemented by a Category of the Core Data Entity Class, except for said accessor which is implemented in the Entity Class itself, hence my question.
In absolute terms, this is perfectly legal. Calling -theProtocolMethod on an instance of TheSubClass would indeed invoke TheSuperClass implementation if TheSubClass itself doesn't implement it. You could even call [super theProtocolMethod] in your subclass implementation, if you wanted.
If TheSubClass was a category on TheSuperClass, the superclass implementation would still be called. However, implementing -theProtocolMethod in the category would replace the super class implementation, so you have to be careful here.
Subjectively, in code-design terms, it's maybe a little odd. You essentially have two separate declarations of the same method to manage, which could potentially cause problems if you tried to refactor. I'm guessing the superclass in your case is a library class that you cannot change. Otherwise, I can't see why TheSuperClass shouldn't just conform to the protocol, rather than declare the method separately.
In theory you're saying the superclass is already compliant with the protocol.
If the compiler complains, you can implement wrapper methods in your subclass that simply call super and return any return value from the call to super.

Protocol inheritance in Objective C

I've got a project which has in it a protocol, a class implementing that protocol, and a subclass of the implementation class. This is our production application.
#protocol ProductionProtocol<NSObject>
#property (nonatomic, retain) NSString *role;
#end
#interface BaseProduction : NSObject<ProductionProtocol>
NSString *role;
#end
#implementation BaseProduction
#synthesize role;
#end
#interface Production : BaseProduction
#end
#implementation Production
#end
I've also got a proof of concept (POC) application, which is implemented as a separate project that includes the production application. In the POC application, I have a protocol that extends the production protocol, and a class that extends the production class.
#protocol POCProtocol<ProductionProtocol>
-(void)cancel;
#end
#interface POC : Production<POCProtocol>
#end
#implementation POC
-(void)cancel{...}
#end
Notice that in the ProductionProtocol, I've got a role NSString which is declared, and implemented in the BaseProduction interface/class. in the POC, I've got a method 'cancel' which is declared in the protocol, but not in the interface/class.
So here's my question: with my class structure set up like this, I get this warning:
Property 'role' requires method '-role' to be defined - use #synthesize, #dynamic or provide a method implementation
I don't understand why I'm getting this warning. Since the synthesized properties are in the base class, they should be available to the POC class - and a quick test seems to confirm that they are. So what am I doing wrong here?
There is no official language definition for Objective-C, but according to Apple:
When a class adopts a protocol, it must implement the required methods the protocol declares, as mentioned earlier. In addition, it must conform to any protocols the adopted protocol incorporates. If an incorporated protocol incorporates still other protocols, the class must also conform to them. A class can conform to an incorporated protocol using either of these techniques:
Implementing the methods the protocol declares
Inheriting from a class that adopts the protocol and implements the methods
However, reports are that GCC doesn't recognize that the property is in an incorporated protocol and is implemented in a superclass. You could change your compiler to Clang, which is reported to handle this in the specified manner, or you could just use #dynamic to tell the compiler that an implementation of the property will be provided at run time (in this case, by inheritance from the superclass).
[XCode 3.2]
The compiler bug is in implementation of protocol inheritance. In the example when compiling POC there are two paths to ProductionProtocol:
POC -> Production -> BaseProduction -> ProductionProtocol
POC -> POCProtocol -> ProductionProtocol
This confuses GCC 4.2, it doesn't confuse Clang (LLVM 1.6, XCode 3.2).
If you change POCProtocol to:
#protocol POCProtocol//<ProductionProtocol>
the error will go away.
You could just comment out the protocol-to-protocol inheritance and leave a TODO to remove when the compiler is fixed.
Looks like a classic compiler writer bug to me, or maybe someone confused with .NET semantics (where you can re-implement interfaces (protocols in Obj-C) along the inheritance chain).
#danyowdee suggests you file a bug report, though as it is not in Clang (I didn't fire up my mothballed XCode 4 to test its compilers) I suspect this is unlikely to be a high priority to get fixed...

Cannot adopt WebKit protocols

#import <WebKit/WebKit.h>
#interface MyClass : NSObject <WebFrameLoadDelegate> {
WebView *webView;
}
cannot find protocol declaration for 'WebFrameLoadDelegate'
WebFrameLoadDelegate is a informal protocol - it is declared as a category of NSObject. To use it you need to declare required methods in class interface and implement them.
When used to declare a protocol, a
category interface doesn’t have a
corresponding implementation. Instead,
classes that implement the protocol
declare the methods again in their own
interface files and define them along
with other methods in their
implementation files.
Directly from Apple Developer Reference:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/WebKit/Protocols/WebFrameLoadDelegate_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40003828
...However, depending on the content being loaded, some of the other methods defined in this protocol may be invoked multiple times. All the methods in this protocol are optional.
So the before answer is not correct in the sense of that it is not necessary to implement all the methods.

What are the angle brackets "<…>" in an Obj-C class interface for?

Can anyone tell me what the angle brackets <...> in an Objective-C class interface do? Like this one (from http://snipt.net/robhawkes/cocoa-class-interface):
#interface MapMeViewController : UIViewController <CLLocationManagerDelegate,
MKReverseGeocoderDelegate, MKMapViewDelegate, UIAlertViewDelegate> { ... }
From my view they look like some sort of type declaration (considering my previous experience in PHP and JavaScript), like we're making sure MapMeViewController is a CLLocationManagerDelegate, MKReverseGeocoderDelegate, MKMapViewDelegate, or UIAlertViewDelegate
Documentation about the #interface syntax don't seem to mention this.
The angle brackets in a class interface definition indicates the protocols that your class is conforming to.
A protocol is almost like an interface in Java or C#, with the addition that methods in an Objective-C protocol can be optional.
Additionaly in Objective-C you can declare a variable, argument or instance variable to conform to several protocols as well. Example
NSObject<NSCoding, UITableViewDelegate> *myVariable;
In this case the class must be NSObject or a subclass (only NSProxy and its subclasses would fail), and it must also conform to both NSCoding and UITableViewDelegate protocols.
In Java or C# this would only be possible by actually declaring said class.
The angle brackets indicate a protocol. They're analogous to interfaces in other languages.
You can also use them in code like a cast to tell the complier to expect an object that conforms to a particular protocol.
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.noteFetcher sections] objectAtIndex:section];
Apple documentation reports the use of brackets; see The Objective-C Programming Language on the chapter 4, on "Adopting a Protocol".
Adopting a protocol is similar in some ways to declaring a superclass. Both assign methods to the class. The superclass declaration assigns it inherited methods; the protocol assigns it methods declared in the protocol list. A class is said to adopt a formal protocol if in its declaration it lists the protocol within angle brackets after the superclass name:
#interface ClassName : ItsSuperclass < protocol list >
Categories adopt protocols in much the same way:
#interface ClassName ( CategoryName ) < protocol list >

Defining categories for protocols in Objective-C?

In Objective-C, I can add methods to existing classes with a category, e.g.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
Is it also possible to do this with protocols, i.e. if there was a NSString protocol, something like:
#interface <NSString> (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
I want to do this since I have several extensions to NSObject (the class), using only public NSObject methods, and I want those extensions also to work with objects implementing the protocol .
To give a further example, what if I want to write a method logDescription that prints an object's description to the log:
- (void) logDescription {
NSLog(#"%#", [self description]);
}
I can of course add this method to NSObject, but there are other classes that do not inherit from NSObject, where I'd also like to have this method, e.g. NSProxy. Since the method only uses public members of protocol , it would be best to add it to the protocol.
Edit: Java 8 now has this with "virtual extension methods" in interfaces: http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf. This is exactly what I would like to do in Objective-C. I did not see this question earning this much attention...
Regards,
Jochen
Short answer: No.
Long answer: how would this work? Imagine you could add methods to existing protocols? How would this work? Imagine we wanted to add another method to NSCoding, say -(NSArray *) codingKeys; This method is a required method that returns an array of the keys used to encoding the object.
The problem is that there are existing classes (like, say NSString) that already implement NSCoding, but don't implement our codingKeys method. What should happen? How would the pre-compiled framework know what to do when this required message gets sent to a class that does not implement it?
You could say "we can add the definition of this method via a category" or "we could say that any methods added via these protocol categories are explicitly optional". Yes, you could do this and theoretically get around the problem I've described above. But if you're going to do that, you might as well just make it a category in the first place, and then check to make sure the class respondsToSelector: before invoking the method.
While it's true that you can't define categories for protocols (and wouldn't want to, because you don't know anything about the existing object), you can define categories in such a way that the code only applies to an object of the given type that has the desired protocol (sort of like C++'s partial template specialization).
The main use for something like this is when you wish to define a category that depends on a customized version of a class. (Imagine that I have UIViewController subclasses that conform to the Foo protocol, meaning they have the foo property, my category code may have need of the foo property, but I can't apply it to the Foo protocol, and if I simply apply it to UIViewController, the code won't compile by default, and forcing it to compile means someone doing introspection, or just screwing up, might call your code which depends on the protocol. A hybrid approach could work like this:
#protocol Foo
- (void)fooMethod
#property (retain) NSString *foo;
#end
#implementation UIViewController (FooCategory)
- (void)fooMethod {
if (![self conformsToProtocol:#protocol(Foo)]) {
return;
}
UIViewController<Foo> *me = (UIViewController<Foo>*) self;
// For the rest of the method, use "me" instead of "self"
NSLog(#"My foo property is \"%#\"", me.foo);
}
#end
With the hybrid approach, you can write the code only once (per class that is supposed to implement the protocol) and be sure that it won't affect instances of the class that don't conform to the protocol.
The downside is that property synthesis/definition still has to happen in the individual subclasses.
extObjC has the NEATEST stuff you can do with Protocols / Categories... first off is #concreteprotocol...
Defines a "concrete protocol," which can provide default implementations of methods within protocol.
An #protocol block should exist in a header file, and a corresponding #concreteprotocol block in an implementation file.
Any object that declares itself to conform to this protocol will receive its method implementations, but only if no method by the same name already exists.
MyProtocol.h
#protocol MyProtocol
#required - (void)someRequiredMethod;
#optional - (void)someOptionalMethod;
#concrete - (BOOL)isConcrete;
MyProtocol.m
#concreteprotocol(MyProtocol) - (BOOL)isConcrete { return YES; } ...
so declaring an object MyDumbObject : NSObject <MyProtocol> will automatically return YES to isConcrete.
Also, they have pcategoryinterface(PROTOCOL,CATEGORY) which "defines the interface for a category named CATEGORY on a protocol PROTOCOL". Protocol categories contain methods that are automatically applied to any class that declares itself to conform to PROTOCOL." There is an accompanying macro you also have to use in your implementation file. See the docs.
Last, but NOT least / not directly related to #protocols is
synthesizeAssociation(CLASS, PROPERTY), which "synthesizes a property for a class using associated objects. This is primarily useful for adding properties to a class within a category. PROPERTY must have been declared with #property in the interface of the specified class (or a category upon it), and must be of object type."
So many of the tools in this library open (way-up) the things you can do with ObjC... from multiple inheritance... to well, your imagination is the limit.
It isn't really meaningful to do so since a protocol can't actually implement the method. A protocol is a way of declaring that you support some methods. Adding a method to this list outside the protocol means that all "conforming" classes accidentally declare the new method even though they don't implement it. If some class implemented the NSObject protocol but did not descend from NSObject, and then you added a method to the protocol, that would break the class's conformance.
You can, however, create a new protocol that includes the old one with a declaration like #protocol SpecialObject <NSObject>.
I think you may be mixing up terms here and there. Extensions, Categories, Protocols, Interfaces and Classes are all different things in Objective-C. In The Objective-C 2.0 Language Apple describes the differences very well, including the benefits and drawbacks to using categories and extensions.
If you think about it, what is a "Category" or "Extension" in the conceptual sense? It's a way of adding functionality to a Class. In Objective-C, protocols are designed to have no implementation. Therefore, how would you add or extend the implementation of something that doesn't have implementation to begin with?
if you're already writing a category, why not just add in the protocol definition in the header right after the category definition?
i.e.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
#protocol MyExtendedProtocolName <NSString>
//Method declarations go here
#end
this way any class that imports the category header will also get the protocol definition, and you can add it into your class..
#interface MyClass <OriginalProtocol,MyExtendedProtocolName>
also, be careful when subclassing NSString, it's a cluster and you may not always get the behaviour you're expecting.
Adam Sharp posted a solution that worked for me.
It involves 3 steps:
Defining the methods you want to add as #optional on a protocol.
Making the objects you want to extend conform to that protocol.
Copying those methods into those objects at runtime.
Check out the link for the full details.