iOS页面回传值 -Delegate/Block/NSNotification/单例
1.Delegate:
https://www.crs811.com/index.php/2016/10/20/swift-protocol-delegate-callback/
2.Block:
https://www.crs811.com/index.php/2016/10/21/swift-closure/
3.NSNotification
首页:
let ObServerName = "crs811" weak var observe : NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NotificationCenter.default.addObserver(self, selector: #selector(ViewController.change), name: NSNotification.Name(rawValue: ObServerName), object: nil) // name: 通知名字 // object: 谁发出的通知,一般传nil // queue: 队列:表示决定block在哪个线程中去执行,nil表示在发布通知的线程中执行 // using: 只要监听到了,就会执行这个block observe = NotificationCenter.default.addObserver(forName: Notification.Name.init(rawValue: ObServerName), object: nil, queue: nil) { (Notification) in //print("-------------",Thread.current) let name = Notification.name //let userInfo = notification.userInfo as! [String:Any] guard let userInfo = Notification.userInfo else { return } let userInfoDic = userInfo as NSDictionary if name == NSNotification.Name(rawValue: self.ObServerName){ self.txtStuNO.text = userInfoDic.object(forKey: "name") as! String } } } func change(notification: Notification) { let name = notification.name //let userInfo = notification.userInfo as! [String:Any] guard let userInfo = notification.userInfo else { return } let userInfoDic = userInfo as NSDictionary if name == NSNotification.Name(rawValue: self.ObServerName){ self.txtStuNO.text = userInfoDic.object(forKey: "name") as! String } } // 一定要移除,不移除的话会存在坏内存访问,移除的话需要定义一个属性observe来接收返回对象,然后在移除方法中移除即可 deinit{ // 移除通知 NotificationCenter.default.removeObserver(self) NotificationCenter.default.removeObserver(observe!) } @IBAction func btnSec(_ sender: UIButton) { let main = UIStoryboard(name: "Main", bundle: nil) let vc = main.instantiateViewController(withIdentifier: "SecViewController") as! SecViewController self.present(vc, animated: true, completion: nil) }
次页:
let ObServerName = "crs811" @IBAction func btnBack(_ sender: UIButton) { NotificationCenter.default.post( name: NSNotification.Name(rawValue: ObServerName), object: self, userInfo: ["name": self.txtStuNO.text]) //回传的用户数据,Dictionary, Image, NSData, ... self.dismiss(animated: true, completion: nil) }
4. KVO
http://www.jianshu.com/p/e036e53d240e
http://www.cnblogs.com/JuneWang/p/3850859.html
5. 单例
Model Class:
创建单例:
final class Single: NSObject { //使用全局变量创建单例 static let shared = Single() private let name = "" private override init() {} //类方法,使用结构体创建单例 class func shareInstance() -> Single { struct single{ static var g_Instance = Single() } return single.g_Instance } }
首页:
let data = Single.shared //Single.shareInstance() if (data.name.length != 0) { self.nameLabel.text = data.name }
次页:
let data = Single.shared data.name = self.nameTextField.text;