我想从其他类 FilterViewController 调用位于 ProductListViewController 中的方法FromFilter:
,
当我尝试调用方法时,我获得了委托的nil值,
这是我的代码段:
ProductListViewController.h
@protocol FirstControllerDelegate<NSObject>
@required
-(void)FromFilter:(NSString *)StrApi;
@end
@interface ProductListViewController : UIViewController<FirstControllerDelegate>{
....
}
@property (nonatomic, assign) id <FirstControllerDelegate> delegate;
ProductListViewController.m
-(void)FromFilter:(NSString *)StrApi{
NSLog(@"------- this is not getting called ---------");
}
FilterViewController.h
@interface FilterViewController : UIViewController{
...
}
@property (nonatomic, assign) id <FirstControllerDelegate> delegate;
FilterViewController.m
- (IBAction)ApplyClicked:(id)sender {
// ----- Here my _delegate is nil ------
if (_delegate == nil) {
[_delegate FromFilter:@"fuyds"];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
请帮忙,我在哪里做错了?
答案 0 :(得分:2)
似乎你没有分配“FilterViewController”的委托属性。
无论何时创建FilterViewController
示例:
FilterViewController *filterViewController = [[FilterViewController alloc]init];
filterViewController.delegate = self;//important
如果您要从ProductListViewController呈现FilterViewController,那么您应该将委托指定为self
答案 1 :(得分:0)
if (_delegate == nil) {
[_delegate FromFilter:@"fuyds"];
}
当然,您的FromFilter
方法并未被调用。仅当_delegate
为零时,您的代码才会调用_delegate
对象的此方法。基本上,您的代码是这样的:
[nil FromFilter];
在Objective C中,您可以向nil
发送消息,它们什么都不做,返回0(nil,NULL)。
答案 2 :(得分:0)
您是否尝试将代码更改为:
- (IBAction)ApplyClicked:(id)sender {
// ----- Here my _delegate is nil ------
if (_delegate != nil) { // != NOT == --> you want to enter the if clause if the delegate is NOT nil
[_delegate FromFilter:@"fuyds"];
}
[self dismissViewControllerAnimated:YES completion:nil];
}