闭包
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/*
OC: block类似于匿名函数, 用于封装代码块, 在特定的时候执行,
执行一些耗时操作
类型: 返回值类型(^block名称)(形参列表)
值:
^(形参列表){
需要执行的代码
}
Swift: 闭包是用于定义函数(Swift中函数就是闭包, 闭包就是一个特殊的函数)
执行一些耗时操作
类型: (形参列表)->返回值类型
值:
{
(形参列表)->返回值类型
in
需要执行的代码
}
*/
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/*
闭包的几种格式
1. 完整写法
loadData ({ () -> () in
print("更新UI")
})
2.如果闭包没有形参, 那么in和in之前的代码都可以省略
loadData ({
print("更新UI")
})
3.如果闭包是函数的最后一个参数, 那么闭包可以写在函数()的后面
loadData (){
print("更新UI")
}
4.如果函数只有一个闭包参数, 那么函数的()可以省略
loadData {
print("更新UI")
}
*/
// in是用于区分代码和描述
// loadData {
// print("更新UI")
// }
loadMoreData { (str) -> () in
print("刷新了UI界面----\(str)")
}
}
//MARK: - 加载数据loadData方法
func loadData(finished: ()->())
{
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
print(NSThread.currentThread())
print("加载数据")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print(NSThread.currentThread())
finished()
})
}
}
//MARK: - 加载更多数据loadMoreData方法
func loadMoreData(finished: (str: String)->())
{
dispatch_sync(dispatch_get_global_queue(0, 0)) { () -> Void in
print("加载更多数据")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// 回到主线程刷新UI
print("回到主线程刷新UI")
finished(str: "走起")
})
}
}
}
闭包的引用循环问题
import UIKit
class ViewController: UIViewController {
// 注意: 在设置闭包属性是可选类型时一定更要用一个()括住闭包的所有的类型, 否则只是指定了闭包的返回值是可选的
// 错误写法: var callback: ()->()?
var callback: (()->())?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// OC中如何解决: __weak typeof(self) weakSelf = self;
// Swift中如何解决: weak var weakSelf = self
// 对应关系: __weak == weak __unsafe_unretained == unowned
// 在Swift开发中, 能不写self就不写slef
// 一般情况下只有需要区分参数, 或者在闭包中使用
// MARK: - 处理循环引用的方法一
/*
weak var weakSelf = self
loadData { () -> () in
print("被回调了")
weakSelf!.view.backgroundColor = UIColor.redColor()
}
*/
// MARK: - 处理循环引用的方法二
loadData { [unowned self] ()-> () in
print("被回调了")
self.view.backgroundColor = UIColor.redColor()
}
}
func loadData(finished: ()->())
{
callback = finished
// 1.加载数据
print("加载数据")
// 2.执行回调
finished()
}
// MARK: - deinit 相当于OC中的dealloc方法
// 只要一个对象释放就会调用deinit方法
deinit
{
print("88")
}
}