我正在尝试更多地了解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:
成功设置了该块。为什么我的块属性为零?
答案 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;
}
}