Objective-C self.delegate在设置后为null

时间:2015-03-14 21:16:43

标签: ios objective-c xcode delegates

我为UIView设置了一个非常简单的委托。但是,当我尝试这样做时:

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

我的self.delegate为空。我检查了setter,设置为委托的类是正确的:

- (void)setDelegate:(id<MyViewDelegate>)delegateClass
{
    // Whether I overwrite this method or not, it's still null.
    NSLog(@"%@", delegate);
    _delegate = delegateClass;
}

这是正确的。但是当它在我的IBAction中被调用时 - 它是空的。

编辑:为了澄清,我只是将其删除以查看传入的内容。如果我不覆盖此方法,它仍然为空。

我的代码:

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

1 个答案:

答案 0 :(得分:2)

MyCollectionViewCell添加此内容:

- (void)dealloc
{
    NSLog(@"MyCollectionViewCell dealloc called")
}

delegate是一个弱引用。因此,如果设置为delegate的实例被释放,它将变为零。上述目的是确认这种情况正在发生。

为什么会这样?如果没有任何东西保持对MyCollectionViewCell实例的强引用,那么它将被释放。

理想情况下,您还希望将NSLog添加到myButtonPressed:。如果您NSLog设置代理人,也会有所帮助。所以你的输出可能是这样的:

Delegate set
MyCollectionViewCell dealloc called <- this would indicate that the delegate becomes nil based on the instance being released
myButtonPressed: hit

考虑到您提供的信息量,这是一个有效的理论。