I've setup a pretty simple delegate, for a UIView. However, when I try to do:
if ([self.delegate respondsToSelector:@selector(selectedPlayTrailer:)]){
[self.delegate selectedPlayTrailer:self];
}
My self.delegate is null. I checked the setter that the class being set as the delegate is right by:
- (void)setDelegate:(id<MyViewDelegate>)delegateClass
{
// Whether I overwrite this method or not, it's still null.
NSLog(@"%@", delegate);
_delegate = delegateClass;
}
And it's correct. But by the time it's called in my IBAction - it's null.
EDIT: To clarify, I only dropped this in to see what was being passed in. If I don't overwrite this method, it's still null.
My code:
MyView.h
#import <UIKit/UIKit.h>
@class MyView;
@protocol MyViewDelegate <NSObject>
@optional
- (void) myDelegateMethod:(MyView *)sender;
@end
@interface MyView : UIView
@property (nonatomic, weak) id <MyViewDelegate> delegate;
- (IBAction)myButton:(id)sender;
@end
MyView.m
@implementation MyView
@synthesize delegate;
- (id)init
{
if (!(self = [super init])) return nil;
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"MyView"
owner:self
options:nil];
return self;
}
- (IBAction)myButton:(id)sender
{
// NOTE: Here, self.delegate is null
if ([self.delegate respondsToSelector:@selector(myDelegateMethod:)]){
[self.delegate myDelegateMethod:self];
}
}
@end
MyCollectionViewCell.m
#import "MyCollectionViewCell.h"
#import "MyView.h"
@interface MyCollectionViewCell() <MyViewDelegate>
@property (nonatomic, strong) MyView *myView;
@end
@implementation MyCollectionViewCell
@synthesize myView;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self){
[self setup];
}
return self;
}
- (void)setup
{
self.myView = [MyView new];
self.myView.frame = CGRectMake(0,0,self.bounds.size.width, self.bounds.size.height);
self.myView.alpha = 0.0;
self.myView.layer.cornerRadius = 5.0f;
self.myView.layer.masksToBounds = YES;
self.myView.delegate = self;
[self addSubview:self.myView];
}
// The delegate method
- (void)myDelegateMethod:(MyView *)sender
{
NSLog(@"This is never called...");
}
@end