我想创建一个可以继承自两个自定义类的类。 你有什么想法吗? 请看下面我的例子:
头等舱:
@interface UIZoomableView : UIView
{
UITapGestureRecognizer *_tapGestureRecognizer;
}
和实现:
- (void)onDoubleTap:(UITapGestureRecognizer *)sender
{
CGSize newSize;
CGPoint centerPoint = self.center;
if ([self isSmall])
{
newSize = [self bigSize];
}
else
{
newSize = [self smallSize];
}
[UIView animateWithDuration:0.3 animations:^{
self.size = newSize;
self.center = centerPoint;
}];
}
第二类:
@interface UIDraggableView : UIView
UIPanGestureRecognizer *_panGestureRecognizer;
@end
实现:
- (void)handlePan:(UIPanGestureRecognizer*)sender
{
..
}
我想创建一个可以缩放和拖动的自定义 View 。 你有什么想法吗? (没有复制代码..)
我认为类似于协议(protocol),但我想要基类的默认值? 我如何使用协议(protocol)或类似协议(protocol)来实现它。
感谢您的回复!
最佳答案
Objective-C 不支持多重继承。您可以使用协议(protocol)、组合和消息转发来实现相同的结果。
协议(protocol)定义了对象必须实现的一组方法(也可能有可选的方法)。组合基本上是包含对另一个对象的引用并在需要其功能时调用该对象的技术。消息转发是一种允许对象将消息传递给其他对象的机制,例如,通过组合包含的对象。
苹果引用:
因此,在您的情况下,组合可能是一种解决方案,下面是示例代码
@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
@implementation MyClass
-(id)initWithA:(ClassA *)anA b:(ClassB *)aB {
a = anA ;
b = aB ;
}
-(void)methodA {
[a methodA] ;
}
-(void)methodB {
[b methodB] ;
}
@end
如果您不想在 MyClass 中实现 ClassA 和 ClassB 中的所有方法,您可以在 MyClass 中使用消息转发来处理所有方法调用。只要 ClassA 和 ClassB 没有任何通用方法,下面就可以正常工作。
@implementation MyClass
-(id)initWithA:(ClassA *)anA b:(ClassB *)aB {
a = anA ;
b = aB ;
}
//This method will be called, when MyClass can not handle the method itself
-(void)forwardInvocation:(NSInvocation *)anInvocation
{
if ([a respondsToSelector:[anInvocation selector]])
[a invokeWithTarget:someOtherObject];
else if ([b respondsToSelector:[anInvocation selector]])
[b invokeWithTarget:someOtherObject];
else
[super forwardInvocation:anInvocation];
}
@end
关于ios - IOS 的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30242799/