0

我正在使用示例学习协议和代表!当我尝试重新创建此示例时,我注意到不遵守此条件:

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

错误在哪里?脚本:

第一次查看.h

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

 @interface DelegateExampleViewController : UIViewController  <EnterAmountDelegate>{

 IBOutlet UILabel *amountLabel;
 }

 -(IBAction)changeAmountPressed;

 @end

第一次查看.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

第二视图.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

提前致谢!

4

1 回答 1

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方法或相对绑定。

于 2012-10-19T11:45:48.493 回答