hgwhittle
hgwhittle

Reputation: 9426

Objective C block property is always nil

I'm trying to learn more about Objective C blocks and how they work. I've set up a simple project with two UIViewControllers embedded in a UINavigationController in Storyboard. I'm attempting to change the background color of the first ViewController's view from the second view controller. Here's some code:

ViewController.m

@implementation ViewController{
    ColorBlock _colorBlock;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"theSegue"]){
        SecondViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
        vc.colorBlock = _colorBlock;
    }
}

- (IBAction)moveToSecondViewController:(id)sender {
    __weak id weakSelf = self;
    _colorBlock = ^{
        [[weakSelf view] setBackgroundColor:[UIColor redColor]];
    };
}

SecondViewController.h

typedef void (^ColorBlock)(void);

@interface SecondViewController : UIViewController

@property (readwrite, copy) ColorBlock colorBlock;

@end

SecondViewController.m

- (IBAction)buttonTapped:(id)sender {
    if(self.colorBlock){
        self.colorBlock();
    }
}

The first ViewController's background color isn't being changed because in the buttonTapped: method of SecondViewController.m, self.colorBlock is nil, causing the block invocation not to be called. I thought I had successfully set the block in prepareForSegue:sender:. Why is my block property nil?

Upvotes: 0

Views: 554

Answers (1)

Rob
Rob

Reputation: 438212

In your prepareForSegue, the destination has already been instantiated. So assuming that SecondViewController is the destination, you can do:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"theSegue"]){
        SecondViewController *vc = segue.destinationViewController;
        NSAssert([vc isKindOfClass:[SecondViewController class]], @"destination is not SecondViewController class");
        vc.colorBlock = _colorBlock;
    }
}

Upvotes: 3

Related Questions