iOS的简单委托示例无法正常工作

时间:2014-02-26 11:31:49

标签: ios objective-c uiviewcontroller delegates protocols

我知道有很多关于在不同视图控制器之间传递消息的问题。我已经检查了所有这些,但我无法让它工作。

我已经按照本教程:http://www.youtube.com/watch?v=XZWT0IV8FrI用导航控制器替换了故事板,但我一遍又一遍地遇到以下问题:'无法找到...的协议声明'

以下是代码:

FirstViewController.h

#import "SecondViewController.h"

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>{
    //In this line above is where I get the error 'Cannot find protocol declaration for SecondViewControllerDelegate'
    IBOutlet UITextField *userNameTextField;
}

@property (nonatomic, strong) UITextField *userNameTextField;

-(IBAction)goNext:(id)sender;

@end

FirstViewController.m

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

@synthesize userNameTextField;


-(void)goNext:(id)sender{

    SecondViewController *secondVC = [[SecondViewController alloc]init];
    secondVC.delegate = self;
    [self.navigationController pushViewController:secondVC animated:YES];   
}

-(void)done:(NSString*)name{

    NSLog(@"BACK in firstVC");
    userNameTextField.text = name;
}

@end

SecondViewController.h

#import "FirstViewController.h"

@protocol SecondViewControllerDelegate <NSObject>

-(void)done:(NSString*)someText;

@end

@interface SecondViewController : UIViewController{

    IBOutlet UITextField *someText;
    IBOutlet UIButton *returnButton;
    id delegate;
}

@property (assign, nonatomic) id <SecondViewControllerDelegate> delegate;
@property (strong, nonatomic) UITextField *someText;

-(IBAction)goBack:(id)sender;

@end

SecondViewController.m

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

@synthesize someText;
@synthesize delegate = _delegate;

-(void)goBack:(id)sender{

    [self.delegate done:someText.text];

    FirstViewController *firstVC = [[FirstViewController alloc]init];

    [self.navigationController pushViewController:firstVC animated:YES];
}

@end

3 个答案:

答案 0 :(得分:2)

您的协议名称是EYSSecondViewControllerDelegate:

@protocol EYSSecondViewControllerDelegate <NSObject>

但你在两个地方称它为SecondViewControllerDelegate:

@interface EYSFirstViewController : UIViewController <SecondViewControllerDelegate>{...
@property (assign, nonatomic) id <SecondViewControllerDelegate> delegate;...

确保名称匹配,它应该可以正常工作。

答案 1 :(得分:2)

SecondViewController goBack实施中,您正在创建一个新的FirstViewController而不是弹出导航控制器,代码应该是......

-(void)goBack:(id)sender{

    [self.delegate done:someText.text];

    [self.navigationController popViewControllerAnimated:YES];

}

并且在你的SecondViewController.h卸载这个#import“FirstViewController.h”,因为它不再需要,可能会让编译器感到困惑

答案 2 :(得分:0)

SecondViewController.h

删除第id delegate;

SecondViewController.m

更新代码 - &gt; [delegate done:someText.text];
'self。'删除 试试吧