委托方法永远不会被调用

时间:2015-09-15 15:28:07

标签: ios delegates

我是IOS的新手,我正在与代表一起调用父ViewController中的方法。

ViewControllerRegistration.h

@protocol RegistrationViewControllerDelegate;
@interface ViewControllerRegistration : UIViewController
@property (nonatomic, weak) id<RegistrationViewControllerDelegate> delegate;
- (IBAction)registerNewUser:(id)sender;
@end

// 3. Definition of the delegate's interface
@protocol RegistrationViewControllerDelegate <NSObject>
-(void)loginResult:(NSString*)loginData;
@end

ViewControllerRegistration.m

- (void)registerNewUser:(id)sender {
 id<RegistrationViewControllerDelegate> strongDelegate = self.delegate;

    // Our delegate method is optional, so we should
    // check that the delegate implements it
    if ([strongDelegate respondsToSelector:@selector(loginResult:)]) {
        [strongDelegate loginResult: @"@WHY YOU NOT BEING CALLED?"];
    }

父母:

ViewController.h

#import "ViewControllerRegistration.h"

@interface ViewController : UIViewController <GPPSignInDelegate,FBSDKLoginButtonDelegate,RegistrationViewControllerDelegate>
@end

ViewController.m

@implementation ViewController
@synthesize signInButton;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

ViewControllerRegistration  *detailViewController = [[ViewControllerRegistration alloc] init];
    // Assign self as the delegate for the child view controller
    detailViewController.delegate = self;
}
//Local Strategy
- (IBAction)navigateToLocalSignUpNavBtn:(id)sender {
    [self performSegueWithIdentifier:@"SegueRegisterUserAction" sender:self];
}

// Implement the delegate methods for RegistrationViewControllerDelegate
-(void)loginResult:(NSString*)loginData{
    NSLog(@"I am called");
    //^Above is never printed. That means delegate method is never called
}

请注意,我的父视图控制器嵌入在导航控制器中。

永远不会调用委托方法。尝试调试,但徒劳无功。

2 个答案:

答案 0 :(得分:1)

昨天,我已在this thread详细解释了这一点。如果您有任何具体问题,请查看并告诉我。我希望这会对你有所帮助。

答案 1 :(得分:1)

您在viewDidLoad中创建的视图控制器与您将要进行的视图控制器不同。这是另一个将在方法结束时解除分配的实例。您需要在prepareForSegue中访问正确的实例并在那里设置代理。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"SegueRegistrationUserAction"]) {
        [(ViewControllerRegistration *)segue.destinationViewController setDelegate:self];
    }
}