What are the key reasons for using #protocols in Objective C? [duplicate] - objective-c

This question already has answers here:
What is a Protocol?
(2 answers)
Closed 10 years ago.
Why would I want to use a protocol rather than create a subclass and inherit the methods..?
Please explain it to me, i'm to confused about this topic, i'm not very pleased with the explanation in the book im reading.
Where do I use protocols instead of other ways to get the methods..? if I can subclass a class and get the methods why would i want to use a protocol where i need to define the methods?

Why would I want to use a protocol rather than create a subclass and
inherit the methods..?
Protocols make it possible for unrelated classes to all implement the same interface. Instances of each of those classes can then be used by a client of the protocol. For example, UITableViewDataSource is a protocol that provides an interface by which a table can ask for data from any object that implements the protocol. The table view doesn't care what the type of the object is so long as it implements the data source interface.
Imagine how unpleasant things would be if all table data sources had to inherit from a common class! Objective-C only provides single inheritance, so you'd effectively be constrained to using only a single kind of object for your data source. With protocols, though, a data source can be a view controller, a model object, or perhaps even a remote object.
To be more specific, protocols allow a form of polymorphism. That means that a single object can take several forms: e.g. view controller, table data source, table delegate, scroll view delegate. Because Objective-C is a single-inheritance language, you only get one of those interfaces via inheritance. The rest you implement yourself, but that often makes sense because you generally adopt a given protocol in order to customize some other object's behavior anyway.

Because subclassing and protocols are two different things. Subclassing extends a class with new functionality while inheriting all previous functionality of a specific class while a protocol, when applied to a class, simply adds functionality to it and doesn't inherit anything from it; what that class is usually doesn't matter.
Protocols are most frequently used for the delegate pattern in Objective-C whereby an object can send a message to another object without caring WHAT that object is (i.e. it's class).
Often times, a delegate is declared as:
#property(nonatomic, assign) id < MyObjectDelegate > delegate;
Notice that the class of the property is id -- in essence, you don't care if the object is a car or a turtle -- all you need to know is that it is an object (id) and that it contractually subscribes to the functions you need it to. So if your delegate is type turtle, you can call [delegate myStateChanged]; or, if your delegate is a car, you can call [delegate myStateChanged]. All you need to know is that, if you send a message to it, it will accept it.
I would look up and read about the use of Objective-C delegates as I think it will really help you understand protocols better and how it's different than subclassing. I don't know if you're familiar with other, object-oriented programming languages, but if so, protocols are most similar to Interfaces in other languages.

Protocols are useful because you can implement many protocols, instead you can only extend a single class.

Related

How to wrap class properties?

there is a conceptional question:
I want to have a wrapper class which forwarding all called selectors to a given object. How do I do this?
And here is why:
I have a library for synchronizing data with a service. And I use Core Data.
For the library I have to create classes of a specific protocol. But I can not use the same protocol for the Core Data subclasses.
My idea is to create a subclass of the specific protocol and forwarding the protocol calls to the Core Data Object.
But there are many subclasses and many properties per subclass and without changing the Core Data subclasses (project specific requirement!)
Is there a way to do this without overwriting every method?
Thanks for your time =)
Implement -forwardingTargetForSelector:. You can return another object to forward unknown messages to. If that is most of what your class will do, you may want to just subclass from NSProxy rather than NSObject. (NSProxy has the advantage that it doesn't implement all of the standard NSObject methods, so you can forward those as well.)
One common problem with this approach is that the compiler will complain that your class does not respond to the selectors you're sending it. The usual way to address this is by requiring that users of your object declare it as id. This can often be inconvenient as well, so this is a bit of a last resort if other approaches are not possible.
But usually the better approach is to make your class a subclass of the target and add the additional methods required for your protocol. Or you can add the additional methods to the Core Data class via a category.
The answer to your specific question is yes. Message Forwarding contains everything you need.
I think you might want to step back and evaluate other options. For example, can you add this functionality to a base class instead of a proxy class.

What are the advantages and disadvantages of using Protocol vs Inheritance? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In objective-c?
I had a class made and then I decided that I want another class that's like the first class. Should I use protocol and ensure that both classes support that protocol or should I create a parent class and decide that the 2 classes inherit from that one class?
Note:
The classes are: Business, Catalog, AddressAnnotation (currently works only on business only) and AddressAnnotationView (currently works only on business only). I want the same thing to work on Catalog. There is also BGGoogleMapCacheForAllAnnotations that manage when the annotations are clumped together (which now should be able to handle both AddressAnnotation for Catalog and Business. Also there is BGGoogleMap View Controller that I want to turn into a parent class.
If you use a protocol, then you have to define methods shared by both class types twice. Protocols are generally reserved for specific patterns, such as the delegation pattern, to add security and make it harder for you to make a mistake, or when several classes already embedded in a class hierarchy need to share common methods and have this sharing be documented in some way. If one class can be represented as a more specialized version of another, you should inherit.
For instance, let's say you you have a Vehicle class in your game that knows how to do all sorts of stuff, such as move around. If you wanted to make a Car class, you'd probably subclass the Vehicle class so that you could inherit all of its method implementations; either to utilize them wholesale or implement your own version of the methods, probably performing some task specific to the subclass before calling the superclass's implementation as well. Subclassing is for when you want to inherit the traits and behaviors of your superclass while modifying it in some way. This is especially true when additional data must be added to the class, such as instance variables, because you can't do that with categories (although you can with a Class Extension, often seen as a sort of private interface). Generally, subclasses have more specialized purposes than their superclasses as a result.
Protocols are just that, protocols. They're there to prevent you from screwing up or forgetting something, and ensure that every object does what it's supposed to, triggering compiler warnings when classes aren't behaving like they are supposed to. This is important for patterns such as delegation, since it's the only way to ensure that the delegate implements the methods you need beyond breaking encapsulation and knowing what type of object your delegate is. For instance, look at the the code below, from one of my projects.
//SGSprite.h
#protocol SGSpriteDelegate
- (BOOL) animation:(int)animationIndex willCompleteFrameNumber:(int)frame forSprite:(id)sender;
#end
#interface SGSprite : NSObject
#property (nonatomic, assign) id<SGSpriteDelegate> delegate;
#end
//SGViewController.h
#interface SGViewController : UIViewController <SGSpriteDelegate>
//...dreadfully boring stuff
#end
Many classes utilize my SGSprite class for rendering textured 2D quads. Sometimes, they need to know when a sprite reaches a certain frame of animation, so SGSprite instances need to call a method on their delegates to let them know when certain frames are reached. The only way to ensure that delegates to instances of this class implement this method, and, indeed, warn me if someone tries to assign an object that doesn't as a delegate, is through the use of a protocol. You'll notice that if I simply make the delegate a plain id I'll get a warning whenever I call this method on my delegate, since its implementation cannot be found, while if I import the delegate's header/statically type the delegate, the class is no longer well encapsulated.
You don't technically need protocols in most cases; you could define all of the methods without a protocol in all of the classes that would ordinarily adhere to said protocol, and everything would work fine. However, these common methods are no longer documented. Thus, beyond the security of knowing certain classes or anonymous objects implement methods you need them to implement, you can also quickly tell what does what and how. Protocols are for when you need to ensure that a class, or instance of a class, implements some method, especially when an object's type shouldn't be known to keep a class encapsulated.
There are a lot of factors that could influence that decision. For one, when you say that the other class is "like the first class", what does that mean? Does it mean that they'll do 90% of the same things in exactly the same way? Does it mean that they'll do a lot of the same kinds of things, but each in a slightly different way?
If many of the existing methods in the first class will work as-is or with little modification in the second class, subclassing lets you get all of those methods "for free" so you can just focus on the differences. If you would need to rewrite most of the code, however, and just want to define the two classes as performing similar actions then a protocol might make more sense.
I've personally used subclassing exclusively, primarily because I haven't run into a situation where a protocol made sense to me in my code - of course, after a while it's more out of habit than conscious decision. When I began converting my app to using Core Data, subclassing fit in very nicely because Core Data offers the ability to create subentities with inherited attributes and relationships. That made it easier to grasp conceptually.
If you think about your current code, you're already subclassing (NSObject, view controllers, etc.) and possibly using protocols (NSCoding, view delegates, etc.). Think about how you use those existing classes and protocols and how those use cases would apply to your own classes.

What is the Difference Between Classes vs Protocols

I'm going through the docs because I am about to implement a protocol instead of a class (something I've never done before), and I'm curious as to the difference between the two.
Can someone give an example in plain words?
Thanks
A class serves as a blueprint for creating one or more objects based on specific implementation of that class.
A good analogy is a form for cutting out butter-cookies. The form‘s attributes (shape, size, height) define the cookies that you can cut out with it. You have only one form (class) but you can create many cookies (instances of that class, ie. objects) with it. All cookies are based on that particular form.
Similarily all objects that are instances of that class are identical in their attributes.
Classes = data and methods (special functions), all sophistically bundled together.
Classes define, what their inner content (data) is + what kind of work (methods) they can do.
The content is based on variables that hold various number types, strings, constants, and other more sophisiticated content + methods which are chunks of code that (when executed) perform some computational operations with various data.
All methods defined in class have their
Definition - that defines the name of the method + what (if any) data the methods takes in for processing and what (if any) data the methods spits out for processing by someone else. All methods defined in class also have Implementation – the actual code that provides the processing – it is the innerworkings of methods.. inside there is code that processes the data and also that is able to ask other methods for subprocessing data. So the class is a very noble type in programming.
If you understand the above, you will understand what a protocol is.
A protocol is a set of one or more method declarations and that set has a name and represents a protocol. I say declarations, because the methods that together are defined by a particular protocol, do not have any implementation code defined.. The only thing that exist is their names declared.
Look above - in class, you have always defined not only what methods the class has, but also how that work will be done. But methods in protocol do not have any implementation.
Lets have a real life analogy again, it helps. If you come to my house to live here for a week, you will need to adhere to my TidyUp protocol. The TidyUp protocol defines three methods - wash the dishes every day, clean the room, and ventilate fresh air. These three methods, I define them..are something you will do. But I absolutely do not care, how the implementation should look like, I just nominaly define the methods. You will implement them, ie.you define how the details of that work (those methods) will look like. I just say, adhere to my protocol and implement it as you see fit.
Finale – You can declare some class. You can separately also declare a protocol. And you can then declare, that this class, in addition to its own methods, will adopt or adhere to that protocol, ie. the class wil implement the protocol’s methods.
The plain words from The Objective-C Programming Language explain the purpose of protocols simply:
Protocols declare methods that can be implemented by any class.
Protocols are useful in at least three situations:
To declare methods that others are expected to implement
To declare the interface to an object while concealing its class
To capture similarities among classes that are not hierarchically related
So, protocols declare methods, but don't provide the implementation. A class that adopts a protocol is expected to implement the protocol's methods.
Delegation is a good example of why a protocol is useful. Consider, for example, the UITableViewDataSource protocol. Any class can adopt that protocol, and any class that does so can be used as the data source for a table. A table view doesn't care what kind of object is acting as its data source; it only cares that the object acting as data source implements a particular set of methods. You could use inheritance for this, but then all data source objects would have to be derived from a common base class (more specific than NSObject). Using the protocol instead lets the table count on being able to call methods like -tableView:willBeginEditingRowAtIndexPath: and -tableView:heightForRowAtIndexPath: without needing to know anything else about the data source.
A protocol is a lot like an interface in Java and other languages. Think of it as a contract that describes the interface other classes agree to implement. It can define a list of required and optional methods that an implementing class will implement. Unlike a class, it does not provide its own implementations of those methods.
the main difference between classes and protocols is that writing protocols is useful to implement delegate methods.
in example we've got class A and class B and we want to call a method in class A from the class B.
you can read a very valuable example of that in this article
http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
reading code is worth a thousand words ;-)
that helped me out the first time I had to use'em
Somewhat less difference than in other languages. An interface (equivalent to a Java/C++ class) defines the data layout of objects and may define some subset of their methods (including the possibility of defining the entire set, of course). A protocol defines a subset of methods only, with no data definition.
Of significance is that a interface can inherit from only one other interface (which can, of course, inherit from an interface which inherits from an interface which inherits ...), but an interface can implement any number of protocols. So two distinct interfaces with no common inheritance (other than NSObject) can both implement the same protocol and thus "certify" that they provide the same functions. (Though with Objective-C you can, with a few tricks, call methods of an interface that aren't externally declared in either the interface declaration or a protocol, so protocols are to a degree just "syntactic sugar" or some such.)
Protocol defines what a class could do, like a Interface in Java or c#
A class is the actual implementation that does the job.
Simple enough? :)

how to inherit from multiple class

Let's say i have a griffon object that needs to be part of the felidae and bird class.
How do i do it ?
I can only make it inherit from 1 class at a time...
This may help...
Multiple inheritance
There is no innate multiple inheritance (of course some see this as a benefit). To get around it you can create a compound class, i.e. a class with instance variables that are ids of other objects. Instances can specifically redirect messages to any combination of the objects they are compounded of. (It isn't that much of a hassle and you have direct control over the inheritance logistics.) [Of course, this is not `getting around the problem of not having multiple inheritance', but just modeling your world slightly different in such a way that you don't need multiple inheritance.]
Protocols address the absence of multiple inheritance (MI) to some extent: Technically, protocols are equivalent to MI for purely "abstract" classes (see the answer on `Protocols' below).
[How does Delegation fit in here? Delegation is extending a class' functionality in a way anticipated by the designer of that class, without the need for subclassing. One can, of course, be the delegate of several objects of different classes. ]
-Taken from http://burks.brighton.ac.uk/burks/language/objc/dekorte/0_old/intro.htm
Multiple Inheritance in Objective C is not supported. The reason for not supporting this mechanism might be the fact that it would have been too difficult to include in the language or the authors thought it is a bad programming and design decision. However, in various cases multiple inheritance proves to be helpful. Fortunately objective C does provide some workarounds for achieving multiple inheritance. Following are the options:
Option 1: Message Forwarding
Message Forwarding, as the name suggests, is a mechanism offered by Objective C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before crashing the objective c runtime provides a second chance for the program to pass the message to the proper object/class which actually responds to it. After tracing for the message till the top most superclass, the forwardInvocation message is called. By overriding this method, one can actually redirect the message to another class.
Example: If there is a class named Car which has a property named carInfo which provides the car’s make, model and year of manufacture, and the carInfo contains the data in NSString format, it would be very helpful if NSString class methods could be called upon the objects of Car class which actually inherits from NSObject.
- (id)forwardingTargetForSelector:(SEL)sel
{
if ([self.carInfo respondsToSelector:sel]) return self.carInfo;
return nil;
}
Source: iOS 4 Developer's cookbook - Erica Sadun
Option 2: Composition
Composition is a cocoa design pattern which involves referencing another object and calling its functionalities whenever required. Composition actually is a technique for a view to build itself based on several other views. So, in Cocoa terminology this is very similar to Subclassing.
#interface ClassA : NSObject {
}
-(void)methodA;
#end
#interface ClassB : NSObject {
}
-(void)methodB;
#end
#interface MyClass : NSObject {
ClassA *a;
ClassB *b;
}
-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;
-(void)methodA;
-(void)methodB;
#end
Source: Objective-C multiple inheritance
Option 3: Protocols
Protocols are classes which contains method to be implemented by other classes who implement the protocol. One class can implement as many as protocols and can implement the methods. However, with protocols only methods can be inherited and not the instance variables.
You can't, per se. But you can have references to as many other objects as you need and you can use multiple protocols.
You can dynamically create a class at runtime and choose the methods of each parent class to inherit. Have a look at the NeXT runtime's documentation here about dynamically creating classes. I did this once just for fun, but I didn't get very far as it gets incredibly messy very quickly.
Edit
It gets more difficult though, because there can only be one superclass, otherwise the keyword super becomes ambiguous.
First, make felidae a subclass of bird. Piece of cake. :-)

Protocol versus Category

Can anyone explain the differences between Protocols and Categories in Objective-C? When do you use one over the other?
A protocol is the same thing as an interface in Java: it's essentially a contract that says, "Any class that implements this protocol will also implement these methods."
A category, on the other hand, just binds methods to a class. For example, in Cocoa, I can create a category for NSObject that will allow me to add methods to the NSObject class (and, of course, all subclasses), even though I don't really have access to NSObject.
To summarize: a protocol specifies what methods a class will implement; a category adds methods to an existing class.
The proper use of each, then, should be clear: Use protocols to declare a set of methods that a class must implement, and use categories to add methods to an existing class.
A protocol says, "here are some methods I'd like you to implement." A category says, "I'm extending the functionality of this class with these additional methods."
Now, I suspect your confusion stems from Apple's use of the phrase "informal protocol". Here's the key (and most confusing) point: an informal protocol is actually not a protocol at all. It's actually a category on NSObject. Cocoa uses informal protocols pervasively to provide interfaces for delegates. Since the #protocol syntax didn't allow optional methods until Objective-C 2.0, Apple implemented optional methods to do nothing (or return a dummy value) and required methods to throw an exception. There was no way to enforce this through the compiler.
Now, with Objective-C 2.0, the #protocol syntax supports the #optional keyword, marking some methods in a protocol as optional. Thus, your class conforms to a protocol so long as it implements all the methods marked as #required. The compiler can determine whether your class implements all the required methods, too, which is a huge time saver. The iPhone SDK exclusively uses the Objective-C 2.0 #protocol syntax, and I can't think of a good reason not to use it in any new development (except for Mac OS X Cocoa apps that need to run on earlier versions of Mac OS X).
Categories:
A category is a way of adding new methods to all instances of an existing class without modifying the class itself.
You use a category when you want to add functionality to an existing class without deriving from that class or re-writing the original class.
Let's say you are using NSView objects in cocoa, and you find yourself wishing that all instances of NSView were able to perform some action. Obviously, you can't rewrite the NSView class, and even if you derive from it, not all of the NSView objects in your program will be of your derived type. The solution is to create a category on NSView, which you then use in your program. As long as you #import the header file containing your category declaration, it will appear as though every NSView object responds to the methods you defined in the catagory source file.
Protocols:
A protocol is a collection of methods that any class can choose to implement.
You use a protocol when you want to provide a guarantee that a certain class will respond to a specific set of methods. When a class adopts a protocol, it promises to implement all of the methods declared in the protocol header. This means that any other classes which use that class can be certain that those methods will be implemented, without needing to know anyting else about the class.
This can be useful when creating a family of similar classes that all need to communicate with a common "controller" class. The communication between the controller class and the controlled classes can all be packaged into a single protocol.
Side note: the objective-c language does not support multiple inheritance (a class can only derive from one superclass), but much of the same functionality can be provided by protocols because a class can conform to several different protocols.
To my understanding Protocols are a bit like Java's Interfaces. Protocols declare methods , but the implementation is up to each class. Categories seems to be something like Ruby's mixins. With Categories you can add methods to existing classes. Even built-in classes.
A protocol allows you to declare a list of methods which are not confined to any particular class or categories. The methods declared in the protocol can be adopted any class/categories. A class or category which adopts a protocol must implements all the required methods declared in the protocol.
A category allows you to add additional methods to an existing class but they do not allow additional instance variables. The methods the category adds become part of the class type.
Protocols are contracts to implement the specified methods. Any object that conforms to a protocol agrees to provide implementations for those methods. A good use of a protocol would be to define a set of callback methods for a delegate (where the delegate must respond to all methods).
Categories provide the ability to extend a current object by adding methods to it (class or instance methods). A good use for a category would be extending the NSString class to add functionality that wasn't there before, such as adding a method to create a new string that converts the receiver into 1337 5P34K.
NSString *test = #"Leet speak";
NSString *leet = [test stringByConvertingToLeet];
Definitions from S.G.Kochan's "Programming in Objective-C":
Categories:
A category provides an easy way for you to modularize the definition of a class into groups or categories of related methods. It also gives you an easy way to extend an existing class definition without even having access to the original source code for the class and without having to create a subclass.
Protocols:
A protocol is a list of methods that is shared among classes. The methods listed in the protocol do not have corresponding implementations; they’re meant to be implemented by someone else (like you!). A protocol provides a way to define a set of methods that are somehow related with a specified name. The methods are typically documented so that you know how they are to perform and so that you can implement them in your own class definitions, if desired.
A protocol list a set of methods, some of which you can optionally implement, and others that you are required to implement. If you decide to implement all of the required methods for a particular protocol, you are said to conform to or adopt that protocol. You are allowed to define a protocol where all methods are optional, or one where all are required.