Using blocks to pass data back to view controller

后端 未结 4 513
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 11:20

I was looking at this question.

One of the answers shows how to use blocks to pass data backwards view the prepareForSegue method. My understanding is t

4条回答
  •  隐瞒了意图╮
    2021-01-06 11:54

    In your view controller 1:

    MyViewControllerClass2* vc2 = [[MyViewControllerClass2 alloc] initWithNibName:@"UIViewController" bundle:[NSBundle mainBundle] completion:^{
        NSLog(@"view2 is closed");
    }]];
    [self.navigationController pushViewController:vc2 animated:YES];
    

    In MyViewControllerClass2.m:

    @interface MarryViewController ()
    
    @property (nonatomic, copy) void(^completion)();
    
    @end
    
    @implementation MarryViewController
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self)
        {
    
        }
        return self;
    }
    
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion
    {
        self = [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
        if( self )
        {
            //store completion block
            _completion = completion;
        }
    
        return self;
    }
    
    -(void)viewDidDisappear:(BOOL)animated
    {
        [super viewDidDisappear:animated];
    
        //call completion block
        _completion();
    }
    

    In MyViewControllerClass2.h:

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil completion:(void(^)())completion;
    

    Just a few notes on how awesome block are:

    1. MyViewControllerClass2 has no idea what is defined in _completion() which is the main point, as this is not of his concern

    2. You could also call _completion() in -dealloc or even on some place where MyViewControllerClass2 will continue to run

    3. You can pass arguments to block functions

    4. You can pass arguments from block functions

    5. Many more :)

    I'm really encouraging people to get good overview on blocks and stat using them as they are pretty cool.

    IMPORTANT!

    While using block you do not declare delegate, the main idea and abstract result of delegate method and using block are the same. Moreover delegate pattern has it's advantages such as better documenting and more strictly usage. Still blocks are way more flexible and(when get used to) easier to use.

    Regards,

    hris.to

提交回复
热议问题