Subclass as delegate of superclass

348 views Asked by At

I have class ImageViewController. It has delegate:

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

I also have class AttachmentViewController that subclass of ImageViewController. In that class I want to get event then image property in changed. So here is my code of it change:

- (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];
                    }
                }];

But I can not use

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

Then I do it I have error:

 No known instance method for selector 'respondsToSelector:'

Why? And how here I need to use this capabilities? Is my implementation ok? Or how can I get this notification?

I think that here will be ok to create clear methods in superclass and override it in subclass if it needs to implement is. Is it best way?

2

There are 2 answers

1
dan On BEST ANSWER

You should declare your protocol as @protocol ImageViewControllerDelegate <NSObject>

This says that any object that conforms to your protocol will also conform to the NSObject protocol that respondsToSelector: is declared in.

1
Andy Poes On

There's really not enough code here to understand what you're trying to do. Generally to setup a delegate you have a weak property on your class that represents the delegate, and a parent to that class's instance would set the delegate.

Here's some pseudo code:

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

Hope this helps!