ios - IOS 的多重继承

标签 ios interface protocols subclass multiple-inheritance

我想创建一个可以继承自两个自定义类的类。 你有什么想法吗? 请看下面我的例子:

头等舱:

@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/

相关文章:

ios - 在带有 10.9 的 xCode 6.1 Mac 上安装 ffmpeg ios 库 armv7、armv7s、i386 和通用

iphone - 我们可以将Core Data类添加到iOS中的框架吗?

go - 可比接口(interface)叫什么?

ios - 通过扩展向协议(protocol)添加功能的原因是什么,为什么不把它放在协议(protocol)本身的定义中呢?

ios - 无法以编程方式移动 UITextView

ios - 向左滑动 iPhone 主屏幕,XCode UI 测试

java - 需要对方法调用进行解释

c# - 通过接口(interface)访问静态属性

swift - swift hashable 协议(protocol)哈希函数是否需要返回唯一值?

swift - 带有关联值的枚举 + 泛型 + 带有关联类型的协议(protocol)