ios委托(delegate)方法未被调用

标签 ios class delegates

我有两个类 - 例如 Class1Class2

Class1 有一个按钮,当按下该按钮时会向 Class2 推送 segue。

此外,当按下按钮时,正在另一个类上进行网络调用。

Class1 代码:

- (IBAction)sellPressed:(id)sender
{
    SPNNetworkEngine *networkEngine = [[SPNNetworkEngine alloc] init];
    networkEngine.delegate = self;
    [networkEngine getFarePrice];
}

Network 类中,我有:

.h文件中

@protocol SPNNetworkEngineDelegate <NSObject>

- (void) farePriceReceivedWithDetails:(id) farePrice;

@end

@property (nonatomic, weak) id delegate;
- (void) getFarePrice;

.m文件中

- (void) getFarePrice
{
 ...........
 .......

  //After all the operations, I delegate
  if ([delegate respondsToSelector:@selector(farePriceReceivedWithDetails:)])
             [delegate farePriceReceivedWithDetails:cost];
  }
}

Class2 我有,

- (void)viewDidLoad
{
    [super viewDidLoad];
     SPNNetworkEngine *networkEngine = [[SPNNetworkEngine alloc] init];
    networkEngine.delegate = self;
}

// Delegate method
- (void) farePriceReceivedWithDetails:(id)farePrice
{
   NSLog(@"FarePrice %@", farePrice);
}

永远不会调用Class2 中的delegate 方法。我在这里做错了什么?

但是当我在 Class1 中编写委托(delegate)方法 -(void)farePriceReceivedWithDetails:(id)farePrice 时,它工作正常。

最佳答案

您的编码方法错误您在您的 Class1 中分配了 SPNNetworkEngine 类并将 SPNNetworkEngine 的委托(delegate)设置为自身。所以委托(delegate)在 class1 中被解雇了。但是你想在 class2 中使用这个方法,所以你必须为这个委托(delegate)分配 class2 对象。

第二点是你必须用这个改变这一行

@protocol SPNNetworkEngineDelegate <NSObject>

- (void) farePriceReceivedWithDetails:(id) farePrice;

@end

@property (nonatomic, strong) id <SPNNetworkEngineDelegate> delegate;
- (void) getFarePrice;   

关于ios委托(delegate)方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25285322/

相关文章:

c++ - 类内外部类&访问

iOS委托(delegate)与协议(protocol)有何不同

c# - 函数内部函数的性能与使用私有(private)函数的对比

objective-c - 使用 ARC 声明委托(delegate)属性的推荐方法

ios - 在 iOS 上使用 Django 和 Alamofire 上传图像

ios - 在 Objective-C 中使用 block 传递数据

ios - 如何在 iOS 中用 MediaItem 中的 Unknown 替换 NULL?

ios - 如何将 iboutlets 插入数组 (swift3)

Java 模板 : array of Template Type in Template

c++ - 我将如何为列表编写 pop_front 函数?