I have two classes. I have defined some methods in it. I need to get those methods from those two classes in a single class without redefinition. Objective C doesn't support multiple inheritance, so how can I achieve this?
Asked
Active
Viewed 4,268 times
2
-
You should only be using inheritance if the relationship between the classes is 'X is a kind of Y'. If you just need to use methods of two classes, just call them (if necessary, you could maintain instances of those classes as properties). – sapi Mar 05 '13 at 04:59
-
I've seen people splice the inheritance hierarchy together so that one of the two desired superclasses inherited from the other, and the most derived class inheriting from that one. This despite there being no "is-a" relationship or need for polymorphism between the two ancestor classes. Whatever you do to solve your problem, I'd advise against that! – Carl Veazey Mar 05 '13 at 05:04
2 Answers
3
Don't use inheritance, use composition.
#import "classname1.h"
#import "classname2.h"
@implementation classname3
-(id)method1
{
id val1 = [classname1 methodToUse];
id val2 = [classname2 otherMethodToUse];
return val1 + val2;
}
@end

Bret Deasy
- 820
- 6
- 14
1
Objective-C dosen't support multiple inheritance. You can create instances of the class and access their methods in new class
@interface class3
{
class1 *c1;
class2 *c2;
}
and access methods using
[c1 yourMethod];
[c2 yourMethod];
you can also use protocols to access methods from multiple class by creating delegate methods and implementing it in other class as explained in http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html

Akbari Dipali
- 2,173
- 1
- 20
- 26