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. :-)
Related
I have a protocol P
#protocol P<NSObject>
{
-(void)foo;
#optional
-(void)bar;
}
And I have bunch of classes (let say a dozen). All of these classes implement protocol P. About half of them implement method bar and all of bar implementations are exactly the same.
What is the best way to share implementation of bar?
Obvious ideas:
1) Create some base class which will implement method bar and let other classes to inherit it.
It's simple to implement. However, I am not big fan of this idea. I prefer class hierarchy to represent entity generalization/specification rather than code reuse.
2) Create a helper and call it from all of classes which needs to implement bar method
Ok. It works. However, if implementation of bar is small (couple of lines in my case) then we will have more overhead (helper class and calling it from each class) than the code itself.
Is there any other (better) methods?
Here are a few ways to share method implementations between classes:
Inheritance. You can make all your classes inherit from a common base class that implements the shared methods. But you can't do this if, for example, you need class A to inherit from UIViewController and class B to inherit from NSManagedObject.
Create a category on a base class shared by all your classes. For example, NSObject is the base class of (virtually) every other class. You can create a category on NSObject to add methods that all classes inherit. If you do this, you should put a prefix your method names to ensure that they won't conflict with other names. E.g. use ronin_foo and ronin_bar instead of just foo and bar.
Create a file containing the method implementations, not surrounded by an #implementation block. Then #include this file in the middle of the #implementation block of each class that needs the methods. Note that the compiler will generate a copy of the machine code for each class, so this could make your program substantially bigger.
At runtime, use the Objective-C runtime API to copy methods from one class to another. You will need to read the Objective-C Runtime Programming Guide and parts of the Objective-C Runtime Reference. You will probably also need to google up some examples.
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.
We know that in Objective-C there are two main root classes: NSObject and NSProxy. There are other roots (mainly for private and legacy purposes) like Object, and NSLeafProxy.
Defining a new root is fairly trivial:
#interface DDRoot <NSObject>
#end
#implementation DDRoot
//implement the methods required by <NSObject>
#end
My question is: why would you ever want to define a new root class? Is there some use-case where it's necessary?
There are two primary reasons to create a new root class; proxying & a new object model.
When proxying, it can be useful to implement a new root class such that you can basically handle any and all of the class/object's behaviors in a custom fashion. See NSProxy.
The Objective-C runtime is flexible enough that you can support a new object model quite easily (where easily discounts the inherent complexity of creating such a beast in the first place). Actually, many of the behaviors that are considered inherent to the runtime -- KVC, KVO, etc.. -- are implemented as a part of the NSObject class itself.
I know of at least one company that -- as of about 8 years ago, at least -- had implemented their own object model as a part of building their ~500k LOC financial analysis engine.
The key, though, is that if you go this route, you don't try to make your classes interact with Foundation/CF/AppKit/UIKit, etc. If you need that, just subclass NSObject already!
It is interesting to note that NSManagedObject is effectively a root class in that it does some pretty seriously custom stuff, but it is a subclass of NSObject so subclasses of NSManagedObject are inter-operable with the rest of the system.
As far as I can tell, there should be no reason for creating your own root class, because short of implementing all of the NSObject protocol methods yourself, you're going to be missing out on a lot of functionality, and going to be making a lot of calls to the Objective-C runtime that should essentially be done for you.
Unless you really had to implement the protocol differently from the default (NSProxy is a special case that does have to), you shouldn't need to make your own root class. I mean, you'd have to be writing a class that cannot fundamentally be represented by NSObject and the protocol as implemented by Apple, and in that case, why are you even writing it in Objective-C?
That's what I think. Maybe someone can come up for a creative use for it.
(People researching the topic should go look at the NSObject Class Reference, NSObject Protocol Reference, 'Core Competencies: Root Class' document, and the 'Root Class' section of the Fundamentals Guide: Cocoa Objects document.)
Objective-C and Cocoa are separate things, and in principle it’s possible to define entirely new application frameworks that don’t use Foundation. The financial analysis people bbum mentioned are a practical example, and I believe they’re still around.
Another use is to make a proxy that’s more minimal than NSProxy, as Mike Ash does here.
Oh, and the private NSInvocationBuilder is a root class, presumably for the same reasons as Mike’s proxy. Capturing invocations for later use is something one might want to recreate.
Companies like the OmniGroup have defined a version of NSObject to use as their own base class for everything.
It's essentially a subclass of NSObject with some debug stuff. Other than that, it's usually a terrible idea to fight the framework.
Find Omni's code here:
https://github.com/omnigroup/OmniGroup
I develop CHDataStructures, a library of Cocoa data structures to supplement those in Foundation. It includes a fair number of classes (stacks, queues, and dequeues) that share common implementation details, so it makes sense to design them with a common parent class which I treat as abstract (Objective-C doesn't natively enforce this concept). For example, CHAbstractCircularBufferCollection encapsulates nearly all the logic for structures that utilize a circular buffer under the covers. Its child classes inherit the core behaviors, and conform to the appropriate protocol so only the methods that pertain to that protocol are added. (So a queue doesn't expose stack methods, etc.)
This has been working just fine, and correctness and coverage are verifiable via unit tests. However, the downside to the current approach is that each concrete subclass has a #import to include the header for the abstract parent class (see this header and implementation) — this means I have to export the parent class headers so client code will compile. It would be ideal if there is a way to use #class in the header rather than #import, so that calling code doesn't have to know or care about the abstract parent class. (It would also simplify and marginally shrink the size of the framework.) However, when I try this:
// CHCircularBufferQueue.h
#import "CHQueue.h"
#class CHAbstractCircularBufferCollection;
#interface CHCircularBufferQueue : CHAbstractCircularBufferCollection <CHQueue>
#end
I get this error, even if I #import CHAbstractCircularBufferCollection.h in the .m file:
Cannot find interface declaration for 'CHAbstractCircularBufferCollection', superclass of 'CHCircularBufferQueue'
I want the compiler to know about the parent class I'm extending, but not require clients to. Is there a way to accomplish what I want to do, and eliminate irrelevant headers from my distribution?
PS - This framework arose mostly from academic curiosity, but I'm considering making changes to make it more like Foundation collections by using class clusters and private subclasses. That would also solve this problem, but I'm curious whether there is a feasible way to do what I'm asking.
If you want to inherit a class, the superclass's #interface (hence the whole superclass hierarchy) must be known so that the ivar offsets of the subclass can be calculated.
You have to #import the .h file for the superclass. As KennyTM points out, this is so the compiler can calculate ivar offsets for the object struct. You can see this in any Cocoa header file. For example, if you open NSArray.h, the very first non-comment line is:
#import <Foundation/NSObject.h>
This holds true for every other class in Cocoa.
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.