Search code examples
iosobjective-cblock

How to pass data from the popped model view controller to the previous view controller using Swift language?


I know that we can switch to VC1 to VC2 using model segue presentViewController. And we can use segue to pass the data from VC1 to VC2 in the prepareForSegue method, like below:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var vc2: VC2ViewController = segue.destinationViewController as! VC2ViewController
    vc2.desiredData = "The data wanted by VC2"
}

However, how can I re-pass the data back to VC1 from VC2 when using dismissViewContoller? I know we can use the block in the objective-C, for example:

// VC1.h file:
typedef void(^SelectedCity)(NSString *);
@property (copy, nonatomic) SelectedCity selectedCity;

// VC1.m file:
__weak VC1ViewController *weakVC1 = self;
_selectedCity = ^(NSString *city) {
    weakVC1.cityLabel.text = "city";
}

// VC2.h file:
typedef void(^SelectedCity)(NSString *);
@property (copy, nonatomic) SelectedCity selectedCity;

// VC2.m file:
if (_selectedCity) {
    _selectedCity(cell.textLabel.text); //get the city from tableView cell
}

The situation is that: I choose the city from VC2's tableView cell, then I got the same city value in VC1.

But, I feel confused about the block. How can we do this to pass data? Does the block seem to be one kind of tunnel overall the whole project? Then we can pass the data from one side, and get the data on the other side.

Before is my understanding about the block. Is this correct? And BTW, how to use block in swift? Thanks a lot.


Solution

  • 3 ways I know you can pass data back to previous viewcontroller.

    1. NSNotification - when u are broadcasting. Use it when call has to be reached in several classes (the class which is registered for notification). relationship - one to many. you are advised to make delegates weak type. Not recommended in your case.

    2. Delegates - Protocol complaint delegates are for one to one class communication. They obj-c/swift based and Best suited for any amount of data. They ain't as fast as Blocks/Closures. relationship - one to one. you are advised to make block copy type. here is the example

    3. Blocks/Closures - Blocks are fast. They are wrapper written over C API. Although their syntax is haphazard. Blocks are used like variables. They contain piece of code you wanna execute at later stage (from another class may be). Blocks create the copy of code statements written inside them including reference. here is the example and here