iOS Developer

swift学习之闭包

2017-01-03  本文已影响29人  CoderLWG

闭包的介绍

闭包的使用

block的用法回顾

@interface HttpTool : NSObject
 - (void)loadRequest:(void (^)())callBackBlock;
@end
@implementation HttpTool
  - (void)loadRequest:(void (^)())callBackBlock{ 
dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
NSLog(@"加载网络数据:%@", [NSThread currentThread]); 
dispatch_async(dispatch_get_main_queue(), ^{ 
 callBackBlock(); }); 
});
}
@end
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
 [self.httpTool loadRequest:^{ NSLog(@"主线程中,将数据回调.%@", [NSThread currentThread]); 
}];
}
block的写法: 
类型: 
返回值(^block的名称)(block的参数) 
值:
 ^(参数列表) { 
  // 执行的代码 
};

使用闭包代替block

class HttpTool: NSObject { 
func loadRequest(callBack : ()->()){ 
dispatch_async(dispatch_get_global_queue(0, 0)) { 
() -> Void in 
print("加载数据", [NSThread.currentThread()]) 
dispatch_async(dispatch_get_main_queue(), {
 () -> Void in callBack() 
          }) 
      }
   }
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
// 网络请求 
httpTool.loadRequest ({ () -> () in 
print("回到主线程", NSThread.currentThread()); 
    }) 
}
闭包的写法:
    类型:(形参列表)->(返回值)
    技巧:初学者定义闭包类型,直接写()->().再填充参数和返回值
值:
{
   (形参) -> 返回值类型 in 
// 执行代码
}

闭包的简写

httpTool.loadRequest({ 
print("回到主线程", NSThread.currentThread()); 
})
httpTool.loadRequest() { 
print("回到主线程", NSThread.currentThread()); 
}
// 开发中建议该写法
 httpTool.loadRequest { 
print("回到主线程", NSThread.currentThread()); 
}

闭包的循环引用

// 析构函数(相当于OC中dealloc方法) 
deinit { 
print("ViewController----deinit")
 }
class HttpTool: NSObject {
 // 定义属性,来强引用传入的闭包 
var callBack : (()->())? 
func loadRequest(callBack : ()->()){ 
dispatch_async(dispatch_get_global_queue(0, 0)) { 
() -> Void in 
print("加载数据", [NSThread.currentThread()]) 
dispatch_async(dispatch_get_main_queue(), { 
() -> Void in 
callBack() 
      }) 
  } 
      self.callBack = callBack 
      }
}
// 解决方案一: 
weak var weakSelf = self 
httpTool.loadData { 
print("加载数据完成,更新界面:", NSThread.currentThread())
 weakSelf!.view.backgroundColor = UIColor.redColor() 
}
 httpTool.loadData {[weak self] () -> () in 
print("加载数据完成,更新界面:", NSThread.currentThread()) 
self!.view.backgroundColor = UIColor.redColor() 
}
httpTool.loadData {[unowned self] () -> () in 
print("加载数据完成,更新界面:", NSThread.currentThread()) 
self.view.backgroundColor = UIColor.redColor() 
}
上一篇下一篇

猜你喜欢

热点阅读