swift中的閉包
類似OC中block
- OC中block 回顧
創(chuàng)建個HttpTool類
.h
@interface HttpTool : NSObject
// void(返回值)(^代表block)(參數(shù))
- (void)loadData:(void(^)(NSString *jsonData))callBack;
@end
.m
#import "HttpTool.h"
@implementation HttpTool
- (void)loadData:(void (^)(NSString *))callBack
{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"發(fā)送網(wǎng)絡(luò)請求:%@", [NSThread currentThread]);
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"拿到數(shù)據(jù),并且進行回調(diào):%@", [NSThread currentThread]);
//調(diào)用block
callBack(@"json數(shù)據(jù)");
});
});
}
@end
控制器中
#import "ViewController.h"
#import "HttpTool.h"
@interface ViewController ()
/** 注釋 */
@property (nonatomic, strong) HttpTool *tools;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tools = [[HttpTool alloc] init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//self.tools 調(diào)用 loadData:方法
//loadData:方法中調(diào)用block,并傳入NSString參數(shù)
//下面的jsonData 即為block回調(diào)的NSString參數(shù)
[self.tools loadData:^(NSString *jsonData) {
NSLog(@"在ViewController拿到數(shù)據(jù):%@", jsonData);
}];
}
- swift中的閉包
- 閉包的類型
() -> ()
閉包的類型: (參數(shù)列表) -> (返回值類型)
創(chuàng)建個HttpTool類
import UIKit
class HttpTool: NSObject {
// 閉包的類型: (參數(shù)列表) -> (返回值類型)
func loadData(callBack : (jsonData : String) -> ()) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
print("發(fā)送網(wǎng)絡(luò)請求:\(NSThread.currentThread())")
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
print("獲取到數(shù)據(jù),并且進行回調(diào):\(NSThread.currentThread())")
callBack(jsonData: "jsonData數(shù)據(jù)")
})
}
}
}
控制器中
import UIKit
class ViewController: UIViewController {
//這里的 HttpTool 不需要導(dǎo)入,swift特性
var tools : HttpTool = HttpTool()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
tools.loadData { (jsonData) -> () in
print("在ViewController拿到數(shù)據(jù):\(jsonData)")
}
}
}
- 閉包中的循環(huán)引用解決
還是上面的例子,針對閉包中的使用 self 造成循環(huán)引用的解決
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/*
解決方法一:
類似oc中 __weak typeof(self) weakself = self 寫法
weakself?.view
如果前面的可選類型,沒有值,后面所有的代碼都不會執(zhí)行
如果前面的可選類型,有值,系統(tǒng)會自動將weakself進行解包,并且使用weakself
*/
weak var weakself = self
tools.loadData { (jsonData) -> () in
// print("在ViewController拿到數(shù)據(jù):\(jsonData)")
weakself?.view.backgroundColor = UIColor.redColor()
}
/*
解決方法二: 推薦使用該方式
swift 特有寫法宿礁,在參數(shù)jsonData前面加上 [weak self]
注意使用也是self? 可選類型,系統(tǒng)自動解包
*/
tools.loadData {[weak self] (jsonData) -> () in
// print("在ViewController拿到數(shù)據(jù):\(jsonData)")
self?.view.backgroundColor = UIColor.redColor()
}
}
- swift 中的 dellloc
// deinit相當(dāng)OC中的dealloc方法,當(dāng)對象銷毀時會調(diào)用該函數(shù)
deinit {
print("ViewController -- deinit")
}