Objective C块属性总是为零

时间:2013-09-12 21:15:43

标签: ios objective-c objective-c-blocks

我正在尝试更多地了解Objective C块及其工作原理。我已经设置了一个简单的项目,其中两个UIViewControllers嵌入在Storyboard的UINavigationController中。我试图从第二个视图控制器更改第一个ViewController视图的背景颜色。这是一些代码:

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

第一个ViewController的背景颜色没有被更改,因为在SecondViewController.m的buttonTapped:方法中,self.colorBlock为nil,导致不调用块调用。我以为我已经在prepareForSegue:sender:成功设置了该块。为什么我的块属性为零?

1 个答案:

答案 0 :(得分:3)

prepareForSegue中,目标已经实例化。因此,假设SecondViewController是目的地,您可以这样做:

-(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;
    }
}