Search code examples
iphoneiosipadblock

Forwarding a block as a property in a class inside a class


I have 3 viewController classes: vA, vB and vC.

I have a method on vA like:

- (void) showMessage:(NSString *)message withTitle:(NSString *)title {
 ...  bla bla
}

I am self.navigationController pushing vB. I want vB to run this method from vA, so what I did was to create a property in vB like this:

@property (nonatomic, strong) void (^showMessage)(NSString *message, NSString *title);

and when I create vB inside vA and just before pushing it, I do this:

vB.showMessage = ^(NSString *message, NSString *title){
        [myself showMessage:message withTitle:title];
};

and I can call showMessage block from vB.

My problem is this: I want to forward this same method to vC that is a third viewController I will be pushing from vB. So this is vC, running a method from vA:

vA pushing vB pushing vC

Is there a simpler way to forward that to vC or do I have to repeat the whole thing of creating another equal property on vC and again wrapping the method in a block. If this is true as it is already a block I will have to do this:

vC.showMessage = ^(NSString *message, NSString *title){
        self.showMessage(message, title);
};

right?

I would like to continue using this block stuff. I am in love with it. 😃

I know I can use notifications, delegates, etc., but this block new stuff is simpler and makes code tight.


Solution

  • You can just assign vC.showMessage = self.showMessage; before pushing to vC. Then call vC.showMessagae(message, title); or when you are in vC, just use self.showMessage(message, title);

    Try it like this,

    in vA.h file,

    Add,

    typedef void (^ShowMessageBlock)(NSString *message, NSString *title);
    

    Then import vA.h file in vB.h file and declare,

    @property (nonatomic, strong) ShowMessageBlock showMessage;
    

    Do the same declaration in vC.h file as well.

    After that when you are pushing to vB,

    vB.showMessage = ^(NSString *message, NSString *title){
            [myself showMessage:message withTitle:title];
    };
    

    and when you are pushing to vC,

    vC.showMessage = self.showMessage;
    

    Then you can use it as self.showMessage(@"", @""); in both classes.