Objective C Protocol代表测试

时间:2012-10-19 11:35:25

标签: objective-c xcode delegates protocols

我正在使用示例研究协议和委托!当我尝试重新创建此示例时,我注意到这个条件不受尊重:

if([delegate respondsToSelector:@selector(amountEntered :)]){blabla}

哪里出错?脚本:

First View .h

 #import <UIKit/UIKit.h>
 #import "EnterAmountViewController.h"

 @interface DelegateExampleViewController : UIViewController  <EnterAmountDelegate>{

 IBOutlet UILabel *amountLabel;
 }

 -(IBAction)changeAmountPressed;

 @end

First View .m

#import "DelegateExampleViewController.h"

@implementation DelegateExampleViewController

-(IBAction)changeAmountPressed
{
EnterAmountViewController * enterAmountVC = [[EnterAmountViewController alloc]init];

enterAmountVC.delegate = self;

} 


-(void)amountEntered:(NSInteger)amount
{
amountLabel.text = [NSString stringWithFormat:@"%i" , amount];
}

@end

第二视图.h

#import <UIKit/UIKit.h>

@protocol EnterAmountDelegate <NSObject>

-(void)amountEntered:(NSInteger)amount;

@end


@interface EnterAmountViewController : UIViewController {

 IBOutlet UITextField *amountTextField;

 id<EnterAmountDelegate> delegate;

 }


-(IBAction)savePressed;

@property(nonatomic,retain) id<EnterAmountDelegate> delegate;

@end

Second View .m

#import "EnterAmountViewController.h"
#import "DelegateExampleViewController.h"

@implementation EnterAmountViewController

@synthesize delegate;


- (void)viewDidLoad {
[super viewDidLoad];

amountTextField.text = @"";
[amountTextField becomeFirstResponder];

}


-(IBAction)savePressed
{

if([delegate respondsToSelector:@selector(amountEntered:)])
{

    [delegate amountEntered:[amountTextField.text intValue]];
    NSLog(@"rugg");
}

}

@end

提前致谢!

1 个答案:

答案 0 :(得分:1)

在方法中:

-(IBAction)changeAmountPressed
{
  EnterAmountViewController * enterAmountVC = [[EnterAmountViewController alloc]init];

  enterAmountVC.delegate = self;
}

您正在堆栈上创建EnterAmountViewController的实例作为局部变量。在范围的末尾,此变量将无法访问。因此,当您执行savePressed时,您正在另一个未设置delegate的对象上执行此操作。

换句话说,检查时

if([delegate respondsToSelector:@selector(amountEntered:)])

它返回NO,因为delegate是nil ...

设置委托的正确方法是使用prepareForSegue机制:

@implementation DelegateExampleViewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

   [(EnterAmountViewController*)segue.destinationViewController setDelegate:self];
}
...

您不需要changeAmountPressed方法也不需要相对绑定。