不调用协议方法,显示委托'nil'

时间:2013-06-22 05:06:26

标签: iphone ios objective-c protocols

我正在使用iPad应用程序而且我遇到了委托问题...协议方法没有被调用。我不确定我错过了什么,这是我的代码。

@protocol pickerLabelProtocol <NSObject>
- (void)selectedPickerData:(UILabel *)sender;
@end

@interface showPickerVC : UIViewController
@property (nonatomic, strong) id <pickerLabelProtocol> delegate;
@end

@implementation showPickerVC
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//i used breakpoint, the 'delegate' is always nil for some reason?
    [self.delegate selectedPickerData:self.mainLabel];
}

----------------------
@interface someViewController : UIViewController <pickerLabelProtocol>
@property (nonatomic, strong) showPickerVC *showPicker;
@end

@implementation someViewController

- (void)selectedPickerData:(UILabel *)sender
{
//protocol method
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.showPicker = [[showPickerVC alloc]init];
    self.showPicker.delegate = self;
}

1 个答案:

答案 0 :(得分:1)

我不能从你的代码中得到任何错误,但我建议你明确当你创建showPickerVC的对象时添加delegate 自我

喜欢这样,

showPickerVC *obj = [[showPickerVC alloc] init];
obj.delegate = self; /// YOur protocol delegate 
.
.
[self presentModalViewController:obj animated:YES];

并且还添加以下代码

@implementation showPickerVC

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

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

}

有关How to create/use of Protocol.

的更多信息