iOS Communication Between Controllers

Generally,in iOS development,delegate is used at most time,but you know when there are too many alert view and alert view's delegate is not nil,the code maybe very confused.

So is there other way to fix this issue? Of course!

The other way is block!So how to use it,please look the demo:

VC1:

typedef void (^MyBlock)(NSString *); 

@interface VC1 : VC {

MyBlock myBlock;

}

@implement VC1

- (void)initBlock {
    self = [super init];  
    if(self)  
    {     
        my = str;  
    }  
    return self;
}

- (IBAction)back:(id)sender {
    NSString* s = txtView.text;  
    if(my)  
    {  
        my(s);  
    }
    [self dismissViewControllerAnimated:YES completion:{}];
}

@end

VC2:

- (IBAction)push {
    VC1 *vc1 = [[VC1 alloc] initBlock:block_copy(^(NSString *str){  
        NSLog(@"%@",str);  
        labShow.text = str; ];
    [self presentViewController:vc1 animated:YES];
}
When presented vc1,and click "back",the text of "txtView" will init the vc2's labShow's text.

Of course you can use delegate to completed this feature.




你可能感兴趣的:(iOS Communication Between Controllers)