Objective C - 对超类的弱引用?

ary*_*axt 15 objective-c super

我试图在块内的超类上调用一个方法.为了避免保留周期,我需要对super的弱引用.我如何获得对超级的弱引用?

[self somethingWithCompletion:^(){
   [super doStuff];
}];
Run Code Online (Sandbox Code Playgroud)

我尝试了以下但是给出了编译错误.

__weak MySuperClass *superReference = super;
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 18

您可以定义一个辅助方法

-(void) helperMethod
{
    [super doStuff];
    // ...
    [super doOtherStuff];
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后呢

__weak MyClass *weakSelf = self;
[self somethingWithCompletion:^(){
    MyClass *strongSelf = weakSelf;
   [strongSelf helperMethod];
}];
Run Code Online (Sandbox Code Playgroud)

使用运行时方法的直接解决方案如下所示:

__weak MyClass *weakSelf = self;
[self somethingWithCompletion:^(){
    MyClass *strongSelf = weakSelf;
    if (strongSelf) {
        struct objc_super super_data = { strongSelf, [MyClass superclass] };
        objc_msgSendSuper(&super_data, @selector(doStuff));
    }
});
Run Code Online (Sandbox Code Playgroud)

缺点(在我看来):

  • 更复杂的代码.
  • 根据"Objective-C运行时编程指南",您不应该直接在代码中调用消息传递函数.
  • 根据方法的返回类型,您必须使用objc_msgSendSuperobjc_msgSendSuper_stret.
  • 对于采用参数的方法,您必须转换objc_msgSendSuper为正确的函数类型(感谢@newacct).