Objective C – Weak reference to super class?-Collection of common programming errors

You could define a helper method

-(void) helperMethod
{
    [super doStuff];
    // ...
    [super doOtherStuff];
    // ...
}

and then do

__weak MyClass *weakSelf = self;
[self somethingWithCompletion:^(){
    MyClass *strongSelf = weakSelf;
   [strongSelf helperMethod];
}];

A direct solution using the runtime methods looks like this:

__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));
    }
});

Disadvantages (in my opinion):

  • More (complicated) code.
  • According to the “Objective-C Runtime Programming Guide”, you should never call the messaging functions directly in your code.
  • Depending on the return type of the method, you would have to use objc_msgSendSuper or objc_msgSendSuper_stret.
  • For methods taking arguments, you have to cast objc_msgSendSuper to the proper function type (thanks to @newacct).