模拟网络请求,封装工具类,使用闭包变量对闭包进行强引用
//
// NetworkRequestTool.swift
// Test
//
// Created by fe on 2017/2/28.
// Copyright © 2017年 fe. All rights reserved.
//
import UIKit
class NetworkRequestTool: NSObject {
var callBack:((_ jisonData:String)->())? = nil //定义闭包变量
//闭包类型:(参数列表)->(返回值类型)
func loadData(callBack:@escaping (_ jisonData:String)->()) {
//在这里对callBack闭包进行强引用,如果以后在控制器中在闭包内用到self则会造成循环引用
self.callBack = callBack;
DispatchQueue.global().async {//异步全局队列
print("耗时操作\(Thread.current)")
DispatchQueue.main.sync {//主队列回掉
callBack("jisonData")
}
}
}
}
//
// ViewController.swift
// Test
//
// Created by fe on 2017/2/28.
// Copyright © 2017年 fe. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let requestTool = NetworkRequestTool()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/*
//第一种解决闭包循环引用的方法 weak var weakSelf = self
//weakSelf?.view.backgroundColor = UIColor.red (1)如果前面的可选类型,没有值,后面的代码不会执行 (2)如果前面的可选类型,有值,系统会自动将weakSelf进行解包,并使用weakSelf
weak var weakSelf = self
requestTool.loadData { (String) in
print("----------\(String)")
weakSelf?.view.backgroundColor = UIColor.red
}
*/
/*
//第二种解决闭包循环引用的用法 [weak self]
requestTool.loadData {[weak self] (String) in
print("----------\(String)")
self?.view.backgroundColor = UIColor.red
}
*/
//第三种解决闭包循环引用的用法 [unowned self]
//__weak :OC的关键字,__weak修饰的弱引用,如果指向的对象销毁,那么指针会立马指向nil(0x0)
//__unsafe_unretained :OC的关键字,__unsafe_unretained修饰的弱引用,如果指向的对象销毁,那么指针依然指向以前的内存地址,很容易产生“野指针”/“僵尸对象”
//unowned :swift关键字,和OC的__unsafe_unretained关键字类似
requestTool.loadData {[unowned self] (String) in
print("----------\(String)")
self.view.backgroundColor = UIColor.red
}
}
deinit {
print("-----------deinit")
}
}