閉包

????閉包的基礎我就不說了同辣,網上多如牛毛,現在來介紹幾種使用的反向傳值的方法谷丸。

第一種:

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

????????weak var weakSelf = self

? ? ? ? aaa.getBackValue(title: "nextViewController", backgroundColor: UIColor.gray) { (backColor, title) in

? ? ? ? ? ? weakSelf.view.backgroundColor = backColor

? ? ? ? ? ? weakSelf.title = title

? ? ? ? ? ? print("selft.title: \(String(describing:? weakSelf.title ))")

? ? ? ? }

? ? ? ? self.present(aaa, animated: true, completion: nil)

}


AAAViewController.swift?

func getBackValue(title: String? = "AAAViewController", backgroundColor: UIColor, lastControllerValue: (_ backgroundColor: UIColor, _ title: String?) -> Void) {

? ? ? ? self?.title = title

? ? ? ?self?.view.backgroundColor =? backgroundColor

? ? ? ? lastControllerValue(UIColor.green, "ViewController")

? ? }

deinit { print("22222222222我釋放了無用的內存!!") }

這樣就可以把閉包中的值傳遞過去舌厨,但是當?lastControllerValue(UIColor.green, "ViewController") 中的??"ViewController" 換為?self.textField.text 時,在返回值中傳遞的是空值忿薇。因為在 還沒跳轉到AAAViewController中時裙椭,就將值返回去了。所以 ? ?lastControllerValue 閉包中的??self.textField.text 為 nil署浩。


第二種:

ViewController.swift ?中

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.changeTitleAndClosure = {

? ? ? ? ? ? (color: UIColor, title: String) in

? ? ? ? ? ? self.view.backgroundColor = UIColor.red

? ? ? ? ? ? self.title = title

? ? ? ? ? ? }?

? ? ? ? self.present(aaa, animated: true, completion: nil)

}


AAAViewController.swift?

var changeTitleAndClosure:((_ color:UIColor, _ title:String) -> Void)?

@objc func lastController() {

? ? ? ? self.dismiss(animated: true, completion: nil)

? ? ? ? self.changeTitleAndClosure?(UIColor.green, self.textField.text!)

}

可以將 TextField 中的值傳遞過去揉燃,但是 定義閉包時參數一定不要為可選值,??:

var changeTitleAndClosure:((_ color:UIColor?, ?_ title:String?) -> Void)?

否則筋栋,在 ViewController 中的閉包不執(zhí)行你雌。若非要空,可給它設置一個默認值二汛,??:

var changeTitleAndClosure:((_ color:UIColor? = UIColor.orange, ?_ title:String? = "12345") -> Void)?


第三種:

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345") { (title) in

? ? ? ? ? ? print("title: \(title)")

? ? ? ? }

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }


AAAViewController.swift

func loadData(color: UIColor, title: String,completion: ?(_ result:String) -> ()) -> () {

? ? ? ? self.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? ? completion(self.textField.text!)

? ? }


第四種:尾隨閉包

增加代碼的可讀性

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345", completion: {

? ? ? ? ? ? (title) in

? ? ? ? ? ? print("~~~~~~~> \(title)")

? ? ? ? })

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }

AAAViewController.swift

func loadData(color: UIColor, title: String,completion: ? (_ result:String) -> ()) -> () {

? ? ? ? self.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? ? ? print("耗時操作 \(Thread.current)")

? ? ? ? ? ? ? ? //回調異步獲取的結果

? ? ? ? ? ? ? ? completion("武松打虎")

? ? }


第五種: 逃逸閉包

關鍵字:?@escaping

????????傳遞給函數的閉包如果不是在函數內調用婿崭,而是在函數內用外部變量保存當前的閉包,在合適的時間再進行調用,需要在閉包參數前加入@escaping關鍵字肴颊,否則編譯器會報錯

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345", completion: {

? ? ? ? ? ? [unowned self](title) in

? ? ? ? ? ? print("~~~~~~~> \(title)")

? ? ? ? ? ? print("weadSelf.view: \(self.view ?? nil)")

? ? ? ? })

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }


AAAViewController.swift

//定義一個閉包屬性

?var completions : ((_ title: String) -> ())?


@objc func lastController() {

? ? ? ? self.dismiss(animated: true, completion: nil)

? ? ? ? self.completions?(self.textField.text!)

? ? }


func loadData(color: UIColor, title: String,completion: @escaping (_ result:String) -> ()) -> () {

? ? ? ? self.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? self.completions = completion

? ? }


? ? deinit {

? ? ? ? print("22222222222我釋放了無用的內存Cフ弧!")

? ? }





第六種: 懶加載

懶加載只會在第一次調用時執(zhí)行創(chuàng)建對象婿着,后面如果對象被釋放了授瘦,則不會再次創(chuàng)建。而oc中會再次創(chuàng)建竟宋。

1.

lazy?var?person?:?Human?=?{??

????????print("懶加載的定義")??

????????return?Human()??

????}()??


//2提完、懶加載改寫為閉包形式 ?

?let?personFunc?=?{?()?->?Human?in ?

????????print("懶加載?-->?閉包")??

????????return?Human()??

????}??

????lazy?var?personDemo?:?Human?=self.personFunc() ?


//3、懶加載的簡單寫法??

lazy?var?person2?:?Human?=?Human() ?



問題: 解決閉包中存在的循環(huán)引用

記住這一點:

VC --strong -- 閉包;

閉包- strong -- VC丘侠;

就造成了循環(huán)引用徒欣,?Swift 屬性的默認 就是強引用:記錄了閉包屬性,然后在閉包中又使用了self蜗字,則產生了循環(huán)引用?

在ARC中打肝,weak本質是一個觀察者模式脂新,一旦對象釋放,則把對象置為nil ?

在MRC中粗梭,是通過assign進行若引用的争便,如果對象釋放,assign的指針還是指向該內地地址断医,會造成野指針?

?__weak?typeof(self)?weakSelf?=?self;?

?//__unsafe_unretained相當于assign滞乙,?

?__unsafe_unretained?typeof(self)?weak1Self?=?self;??

方式一:

關鍵字: weak

注意:weak只能修飾var,不能修飾let鉴嗤,因為如果weak的指針在運行時會被修改酷宵,會自動設置為nil??

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345", completion: {

? ? ? ? ? ? (title) in

? ? ? ? ? ? print("~~~~~~~> \(title)")

? ? ? ? ? ? print("weadSelf.view: \(self.view ?? nil)")

? ? ? ? })

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }


AAAViewController.swift

// 定義一個閉包屬性

var completion : ((_ title: String) -> ())?

func loadData(color: UIColor, title: String,completion: @escaping (_ result:String) -> ()) -> () {

? ? ? ? weak var weakSelf = self

? ? ? ? weakSelf?.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? completion("武松打虎")

? ? }


? ? deinit {

? ? ? ? print("22222222222我釋放了無用的內存!躬窜!")

? ? }


方式二:

推薦:

[weak?self]表示閉包中的self都是若引用

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345", completion: {

? ? ? ? ? ? [weak self](title) in

? ? ? ? ? ? print("~~~~~~~> \(title)")

? ? ? ? ? ? print("weadSelf.view: \(self?.view ?? nil)")

? ? ? ? })

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }

AAAViewController.swift

//定義一個閉包屬性

var completion : ((_ title: String) -> ())?

func loadData(color: UIColor, title: String,completion: @escaping (_ result:String) -> ()) -> () {


? ? ? ? self.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? completion("武松打虎")

? ? }


? ? deinit {

? ? ? ? print("22222222222我釋放了無用的內存=娇选!")

? ? }


方式三:

關鍵字:

[unowned?self]:表示閉包中的self為assign荣挨,如果self被釋放男韧,則指針地址不會被釋放,容易導致出現野指針?

ViewController.swift

@objc func nextController() {

? ? ? ? let aaa = AAAViewController()

? ? ? ? aaa.loadData(color: UIColor.red, title: "12345", completion: {

? ? ? ? ? ? [unowned self](title) in

? ? ? ? ? ? print("~~~~~~~> \(title)")

? ? ? ? ? ? print("weadSelf.view: \(self.view ?? nil)")

? ? ? ? })

? ? ? ? self.present(aaa, animated: true, completion: nil)

? ? }


? AAAViewController.swift

//定義一個閉包屬性

?var completion : ((_ title: String) -> ())?

func loadData(color: UIColor, title: String,completion: @escaping (_ result:String) -> ()) -> () {


? ? ? ? self.view.backgroundColor = color

? ? ? ? print("----->title: \(title)")

? ? ? ? completion("武松打虎")

? ? }


? ? deinit {

? ? ? ? print("22222222222我釋放了無用的內存Dⅰ此虑!")

? ? }

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市口锭,隨后出現的幾起案子朦前,更是在濱河造成了極大的恐慌,老刑警劉巖鹃操,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件韭寸,死亡現場離奇詭異,居然都是意外死亡荆隘,警方通過查閱死者的電腦和手機恩伺,發(fā)現死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來椰拒,“玉大人晶渠,你說我怎么就攤上這事∪脊郏” “怎么了褒脯?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長缆毁。 經常有香客問我番川,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任爽彤,我火速辦了婚禮,結果婚禮上缚陷,老公的妹妹穿的比我還像新娘适篙。我一直安慰自己,他們只是感情好箫爷,可當我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布嚷节。 她就那樣靜靜地躺著,像睡著了一般虎锚。 火紅的嫁衣襯著肌膚如雪硫痰。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天窜护,我揣著相機與錄音效斑,去河邊找鬼。 笑死柱徙,一個胖子當著我的面吹牛缓屠,可吹牛的內容都是我干的。 我是一名探鬼主播护侮,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼敌完,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了羊初?” 一聲冷哼從身側響起滨溉,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎长赞,沒想到半個月后晦攒,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡得哆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年勤家,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柳恐。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡伐脖,死狀恐怖,靈堂內的尸體忽然破棺而出乐设,到底是詐尸還是另有隱情讼庇,我是刑警寧澤,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布近尚,位于F島的核電站蠕啄,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜歼跟,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一和媳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧哈街,春花似錦留瞳、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至作箍,卻和暖如春硬梁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背胞得。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工荧止, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人阶剑。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓罩息,卻偏偏與公主長得像,于是被迫代替她去往敵國和親个扰。 傳聞我的和親對象是個殘疾皇子瓷炮,可洞房花燭夜當晚...
    茶點故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內容

  • 一、導語: 最近在研究Swift中返向傳值递宅,其中遇到了一些問題娘香,想把自己學習的經過記錄下來,希望可以幫助那些需要學...
    瘋狂的小碼農閱讀 685評論 0 4
  • 一 办龄、AppDelegate.swift 里設置導航控制器 import UIKit @UIApplication...
    天涯海角我愛你閱讀 343評論 0 0
  • 在上一篇文章Swift中的變量和常量中我總結了一些自己對于變量和常量的認識烘绽,最近學習了閉包,順便給大家分享一下關于...
    老板娘來盤一血閱讀 18,688評論 16 87
  • 1俐填、init 命令 2安接、pull 命令 3、checkout 命令 4英融、branch 命令 5盏檐、add 命令 6、...
    倔強的溫柔1412閱讀 207評論 0 0
  • 人生大概沒有輸贏 只是遭遇不同讓人們這么覺得 遭遇的不同又同時疊加給人不同的性格效應 性格的不同又同時會決定所謂的...
    歡謹一粟閱讀 120評論 0 0