委托方法未被调用? [英] Delegate method not being called?

查看:105
本文介绍了委托方法未被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图控制器与委托方法,应该被调用,但它不?

I have a view controller with a delegate method that should be called, but it doesn't?

NotifyingViewController.h

NotifyingViewController.h

@protocol NotifyingViewControllerDelegate <NSObject>
@required
- (void)iWasAccepted;
@end

@interface NotifyingViewController : UIViewController

@property (nonatomic, weak) id<NotifyingViewControllerDelegate> delegate;

NotifyingViewController.m

NotifyingViewController.m

-(void)someMethod{
        [self.delegate iWasAccepted];
        [self dismissViewControllerAnimated:YES completion:nil];
}

NotifiedViewController.h

NotifiedViewController.h

#import "NotifyingViewController.h"  
@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>

NotifiedViewController.m

NotifiedViewController.m

-(void)iWasAccepted{
    [self saveIntoDB];
    NSLog(@"DELEGATE RAN");
}

由于某种原因,应该通知的控制器不是。通知控制器会关闭,这意味着警告代理运行的方法,但委托不运行该函数,因为它不是NSLog。任何想法为什么?

For some reason, the controller that should be notified isn't. The Notifying controller does dismiss meaning the method that alerts the delegate IS run, but the delegate doesn't run the function because it doesn't NSLog. Any ideas why?

推荐答案

你不能只指定一个对象符合协议。您还必须将该对象分配为委托。当你分配/ init的NotifyingViewController的实例,设置其委托为self,你应该很好。

You can't just specify that an object conforms to a protocol. You must also assign that object as the delegate. When you alloc/init the instance of NotifyingViewController, set its delegate to self and you should be fine.

NotifyingViewController *notifyingInstance = [[NotifyingViewController alloc] init];
[notifyingInstance setDelegate:self];

重要的是要做到这一点,并指定类符合协议,已经在使用此行。

It is important to both do this, and specify that the class conforms to the protocol, which you're already doing with this line.

@interface NotifiedViewController : UIViewController <NotifyingViewControllerDelegate>

此外,调用delegate方法时,最好将函数调用包装在 responsesToSelector:检查。

Additionally, when calling delegate methods, it's good practice to wrap the function calls in respondsToSelector: checks.

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

这篇关于委托方法未被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆