【问题标题】:Subclass as delegate of superclass子类作为超类的代表
【发布时间】:2015-06-10 16:01:42
【问题描述】:

我有课ImageViewController。它有委托:

@protocol ImageViewControllerDelegate
@optional
- (void)singleTapGestureRecognizer:(UITapGestureRecognizer *)gesture;
- (void)imageDidLoaded;

我还有 AttachmentViewController 的类 ImageViewController 的子类。在那个类中,我想获取事件,然后更改图像属性。所以这是我的代码更改:

- (void)setImage:(UIImage *)image
{
// * Assign image with animation
[UIView transitionWithView:self.imageView
                  duration:k_DURATION_imageAppearence
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations: ^{
                    self.imageView.alpha = 1;
                } completion:^(BOOL finished) {

                    if ([self respondsToSelector:@selector(imageDidLoaded)]) {
                        [self.delegate imageDidLoaded];
                    }
                }];

但是我不能用

if ([self.DELEGATE respondsToSelector:@selector(imageDidLoaded)]) 

然后我这样做我有错误:

 No known instance method for selector 'respondsToSelector:'

为什么?以及如何在这里使用此功能?我的实施好吗?或者我怎样才能得到这个通知?

我认为在这里可以在超类中创建明确的方法并在子类中覆盖它,如果它需要实现的话。这是最好的方法吗?

【问题讨论】:

  • 先学习单例类和委托,然后你就能解决你的问题。你缺乏关于委托的知识
  • @nischalhada 这与单例或委托无关。查看问题的当前答案。
  • 不便敬请见谅
  • 希望问题解决

标签: ios objective-c inheritance uiviewcontroller delegates


【解决方案1】:

您应该将您的协议声明为@protocol ImageViewControllerDelegate <NSObject>

这表示任何符合您的协议的对象也将符合声明respondsToSelector:NSObject 协议。

【讨论】:

【解决方案2】:

这里没有足够的代码来理解你想要做什么。通常,要设置委托,您的类上有一个表示委托的弱属性,并且该类实例的父级将设置委托。

这是一些伪代码:

@protocol SomeDelegateProtocol<NSObject>
- (void)someMethod:(id)someObject;
@end

@interface SomeClass:NSObject

@property (nonatomic, weak) id<SomeDelegateProtocol>delegate;

@end

@implementation SomeClass

- (void)someFunction {
    if ([self.delegate respondsToSelector:@selector(someMethod:)]) {
        // do code stuff
    }
}

@end

///////////

@implementation SomeParentClass

- (void)someOtherFunction {
    SomeClass *instance = [SomeClass new];
    instance.delegate = self; // assuming self implements SomeDelegateProtocol, otherwise you get a warning
}

希望这会有所帮助!

【讨论】:

  • 你没有抓住重点。问题很清楚,它与提供的错误有关。请看“丹”的答案。
猜你喜欢
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 2019-02-06
相关资源
最近更新 更多