Ios 用于调用其他类的委托方法
我读过不同的授权方法帖子,但我仍然不知道哪里错了 我想从我的主ViewController(名为mainVC)显示一个自定义弹出窗口(一个xib文件及其关联的popover视图控制器名为popoverVC)。在我的弹出窗口中有一个按钮,用于在mainVC内的文本字段中显示文本。我的问题如下:Ios 用于调用其他类的委托方法,ios,class,methods,action,delegation,Ios,Class,Methods,Action,Delegation,我读过不同的授权方法帖子,但我仍然不知道哪里错了 我想从我的主ViewController(名为mainVC)显示一个自定义弹出窗口(一个xib文件及其关联的popover视图控制器名为popoverVC)。在我的弹出窗口中有一个按钮,用于在mainVC内的文本字段中显示文本。我的问题如下: 由Xib文件中的my按钮调用的popoverVC中的方法“firstMethod:”正在工作(控制台上显示NSLog消息“firstMethod called!”) 此方法“firstMethod”调用位
- 由Xib文件中的my按钮调用的popoverVC中的方法“firstMethod:”正在工作(控制台上显示NSLog消息“firstMethod called!”)
- 此方法“firstMethod”调用位于mainVC中的另一个方法“secondMethod”。此方法在popoverVC内部的协议声明中定义,并且也在工作(在控制台上:NSLog消息“secondMethod Called!”,除了前面的“firstMethod Called”)
@protocol mainVCDelegate <NSObject>
@optional
- (void)insertValue;
@end
#import...
//method called by the button in Xib file and supposed to call the method in mainVC to then display text inside a textfield in mainVC
- (IBAction)updateTextFieldInMainVC:(id)sender {
NSLog(@"firstMethod called!");
mainVC *mvc = [[mainVC alloc] init];
[mvc insertValue];
}
@interface mainVC : UIViewController <mainVCDelegate>
- (void)insertValue {
NSLog(@"secondMethod called!"); ---> this is displayed on the console
self.textfield.text = @"sometext"; ---> this is not displayed in the textfield
}
mainVC.h:
@protocol mainVCDelegate <NSObject>
@optional
- (void)insertValue;
@end
#import...
//method called by the button in Xib file and supposed to call the method in mainVC to then display text inside a textfield in mainVC
- (IBAction)updateTextFieldInMainVC:(id)sender {
NSLog(@"firstMethod called!");
mainVC *mvc = [[mainVC alloc] init];
[mvc insertValue];
}
@interface mainVC : UIViewController <mainVCDelegate>
- (void)insertValue {
NSLog(@"secondMethod called!"); ---> this is displayed on the console
self.textfield.text = @"sometext"; ---> this is not displayed in the textfield
}
看来你错过了授权的重要部分。我建议阅读关于授权的文章。但同时,这是你所缺少的 委派允许popoverVC不知道mainVC。您正在创建一个mainVC实例,并直接调用它的方法
insertValue
,这不是委托
在popoverVC.h中
@protocol mainVCDelegate <NSObject>
@optional
- (void)insertValue;
@end
@interface popoverVC : UIViewController
@property (weak) id <mainVCDelegate> delegate;
@end
在mainVC.h
@interface mainVC : UIViewController <mainVCDelegate>
记录self.textfield并查看它的内容。它是(null)。。。我不知道如何访问它…编辑后回答是极好的。可能应该在编辑之前删除这些内容。谢谢你的帮助,我会读这篇文章的。但你的解决方案似乎不起作用。在popoverVC中,不使用[delegate insertValue]调用insertValue方法。尽管我在mainVC的didLoad方法中添加了popover.delegate=self。。。不再有第二条NSLog语句:-(我试图通过[self.delegate insertValue]更改[delegate insertValue],但它也不起作用…@Trichophyton-答案对我来说是正确的。一个很好的调试技巧是,你几乎可以记录任何东西。所以我会,popover调用[self.delegate insertValue],NSLog委托,如下所示:NSLog(@“%@”,self.delegate);它应该记录mainVC的一个实例。@danh-我在[self.delegate insertValue]之后做了NSLog,我注意到消息没有发送,即[self.delegate respondsToSelector:@selector(insertValue)]应该返回否。我根据您的建议测试self.delegate,它返回(null),没有创建mainVC的实例。我不知道为什么。。。