This question already has answers here:
#interface and #protocol explanation?
(3 answers)
Class vs. Interface
(10 answers)
Closed 9 years ago.
I think that, except for the name, the protocols are much better suited to work as "interfaces" between classes. They do all that the #interfaces do (exposing properties and methods) and on top of that different classes can implement the same protocol which is a huge advantage in tandem with the dynamical nature of Objective-C. So why do we still use #interfaces? What advantages do they bring comparing with protocols? (I hope to get more out of this question than a "they are explicit in what they do" or "closed as not constructive".)
A delegate protocol needs to be defined as such
#protocol
//methods
#end
it can be put in any .h class, you just need to import i t whenever you are going to use it.
A protocol is not like a java interface, a protocol is an adapter that allows two classes to works together. Basically it says, if you want class A to send you messages about its state and actions these are the methods it will call on its delegate that you must implement. Its not like an interface because an interface says if you want to subclass this class you must implement these methods, the protocol says if you want to interact with this class you must implement these methods, so its somewhat different.
Objective C interfaces, delegates, and protocols
Related
This question already has answers here:
Creating an abstract class in Objective-C
(21 answers)
Closed 7 years ago.
I've realized there's no abstract classes in Objective-C. Is there any way to achieve the same functionality in some other way (a class that can't be instantiated, or methods that MUST be overridden by their subclass)?
It depends exactly what you want. If you would just use the class as an interface with no implementation then using a protocol instead is best. If you need some base or default implementation then you either document that the class shouldn't be instantiate do directly (common nowadays I think) or you implement the class to throw exceptions if it is instantiated directly (uncommon nowadays). Also throw exceptions in any methods that should be implemented by a subclass and are called on the superclass.
Unless you're creating a framework that will be delivered to other developers it's generally not worth the effort to implement, just document.
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.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Understanding #Protocols in Objective-C
Objective C protocols usage
I just started learning objective C and I do not seem to get my head around protocols very well. My understanding of Protocols in objective-C is that, you specify some method definition without actually writing the code for it. What that means is that, whoever decides to inherit my class must implement all my required methods.
My question here is that, Isn't protocols creating an extra over-head which is not really needed. If I need a method in my new class I can just implement it. Why do I need to inherit from a protocol?
Why cant I just ignore using protocols and just create methods as I need them.
Among other things, protocols are a way of letting the compiler help you avoid common errors. In this case, you can specify that one class will be calling specific methods on another class (often a delegate). The compiler will then check to make sure the other class (delegate) actually implements those methods and, if not, give you a warning message. Getting a message at compile time is preferable to crashing at runtime due to an undefined selector (method).
My question here is that, Isn't protocols creating an extra over-head which is not really needed.
there is no added overhead.
If I need a method in my new class I can just implement it. Why do I need to inherit from a protocol?
well, you can certainly declare a subclass for your common implementation, if that is an ideal path for your needs. if you try this, you will likely run into the issues i outline below.
protocols are often used because they are not actual physical types. it is an interface of methods and/or other protocols. usually, they are small and specialized. since objc does not offer multiple inheritance, protocols come in really handy for short extensions.
look at types which are complex subclasses and inherit one or more protocols; take NSString <NSCoding, NSCopying, NSMutableCopying, NSObject> as an example. knowing that objc uses single inheritance, consider how you would implement this class and 'inherit' from all those protocols - then consider the effect it would have on clients when passing those types after you have implemented this for all Foundation types. the class hierarchy and interfaces get very messy. the number of variations in many classes would explode to accommodate all those types as parameters. most people would stop before that point, and just drop type safety -- also a very bad idea. with a protocol, you can have "implements this interface" and type safety all in a simple language feature (multiple inheritance gets quite ugly quite quickly).
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.