作为参数传递一个objective-c协议代理

5
当我将一个Objective-C协议作为参数传递时,当并且该委托被用来触发其中一个方法时,该方法不会触发。
我正在使用从Paypal iOS SDK定义的委托。
@protocol PayPalPaymentDelegate <NSObject>
    - (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController;
@end

我有一个实现了协议的UIViewController:

//simpleviewcontroller.h
@interface SimpleViewController : UIViewController<PayPalPaymentDelegate>

并且具有以下方法签名:

// HelperFunctions.m
+ (void) doSomething: (id<PayPalPaymentDelegate>)paypalDelegate
{
    // the selector 'payPalPaymentDidCancel' DOES fire
    [paypalDelegate performSelector:@selector(payPalPaymentDidCancel:) withObject:self]
}


// called from simpleviewcontroller.m that implements PayPalPaymentDelegate
[HelperFunctions doSomething: self]

问题在于当PayPal返回结果时,它不会触发委托。
// code inside of the 'success' block of an AFNetworking call
PayPalPaymentViewController *paymentViewController;
paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment    
                                                             configuration:paypalConfiguration   
                                                             delegate:paypalDelegate];

在这里传递给“delegate”的paypalDelegate从未被PayPal触发。但是,如果通过simpleviewcontroller.m完成而不是通过doSomething方法完成,则会触发它。

我觉得你应该同时传递SimpleViewController,因为委托方法也需要视图控制器。它在SimpleViewController上工作是因为你传递了“他”,但由于你传递了“HelperFunctions”对象,它不起作用。(哦等等,委托!只需使用paypalDelegate而不是self。) - EDUsta
在你写 [paypalDelegate performSelector:@selector(payPalPaymentDidCancel:) withObject:self]; 的那一行,self 是指什么?毕竟它是在一个类方法中。 - Alex Basson
1个回答

1
创建了 paymentViewController 后,您是否在某个地方保留了 paypalDelegatePayPalPaymentViewController 只保留对委托的弱引用,因此如果没有保留,它将在创建 PayPalPaymentViewController 的范围结束时被 ARC 释放(因此不会触发任何方法)。

我根本没有将paypalDelegate存储在任何变量中,只是将Self传递给doSomething方法。我应该创建一个强变量并将paypalDelegate放入其中吗?请注意,在方法中使用performSelector确实有效,这是否表明委托的引用没有丢失? - Shane
doSomething: 方法中创建 PayPalPaymentViewController 的代码是什么?虽然我假设您的视图控制器(委托)在视图控制器层次结构中,因此可能不会被释放?在委托对象的 dealloc 方法中放置一个日志,并检查它是否被释放。 - George Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接