一、有关回调

我们知道,执行函数的时候,一般都有return作为返回参数了,那有return了为什么还要回调呢?

回调是为了实现异步的返回,在某些特殊的情况下,比如你执行的函数是一个长时间运行的函数,并不能直接返回给你结果,为了不影响源程序其他步骤的执行,你得继续执行下去,等那边产生结果了再“主动告诉你”结果是什么。

其原理不外乎:A调用B中函数,传递参数和自身指针,B执行完成再通过传递过来的指针重新调用A中函数。

在iOS开发中,实现回调的方式有:Delegate和Block。前者用变量指针实现,后者用函数指针实现。

假如我现在有一个processData的类用来处理数据,处理完之后回调给主要的Class。

二、Swift中实现回调

1.代理模式:利用protocol+引用变量

processData.swift

//
// ProcessData.swift import UIKit
//定义协议
protocol callBackDelegate {
func callbackDelegatefuc(backMsg:String)
} class ProcessData: NSObject{
//定义一个符合改协议的代理对象
var delegate:callBackDelegate?
func processMethod(cmdStr:String?){
if((delegate) != nil){
delegate?.callbackDelegatefuc("backMsg---by delegate")
}
}
}

ViewController.swift

//
// ViewController.swift import UIKit //继承该协议
class ViewController: UIViewController,callBackDelegate{ override func viewDidLoad() {
super.viewDidLoad()
let process=ProcessData() //把process的delegate变量指针指向自己,那样process就能调用自己类里的函数了
process.delegate=self //执行函数
process.processMethod("startProcess")
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
} //delegate回调
func callbackDelegatefuc(backMsg:String){
print(backMsg)
}
}

2.利用闭包实现:

闭包在Objective-C中被称为Block,在Swift中被成为Closure(在Java中称为Lambda)

2.1利用闭包变量实现回调

processData.swift

//
// ProcessData.swift import UIKit class ProcessData: NSObject{
//定义block
typealias fucBlock = (backMsg :String) ->()
//创建block变量
var blockproerty:fucBlock! func processMethod(cmdStr:String?){
if let _ = blockproerty{
blockproerty(backMsg: "backMsg---by block property")
}
}
}

ViewController.swift

//
// ViewController.swift import UIKit class ViewController: UIViewController{ override func viewDidLoad() {
super.viewDidLoad()
let process=ProcessData() //block回调
process.blockproerty={ (backMsg) in
print(backMsg)
} //执行函数
process.processMethod("processStart")
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

2.2 把闭包写入函数作参数实现快速回调,可见这是一种代码最为简洁的方案

processData.swift

//
// ProcessData.swift import UIKit class ProcessData: NSObject{
//定义block
typealias fucBlock = (backMsg :String) ->() func processWithBlock(cmdStr:String?,blockProperty:fucBlock){
blockProperty(backMsg :"backMsg---by block inside func")
}
}

ViewController.swift

//
// ViewController.swift import UIKit class ViewController: UIViewController{ override func viewDidLoad() {
super.viewDidLoad()
let process=ProcessData() //函数内回调
process.processWithBlock("bbb") { (backMsg) in
print(backMsg)
}
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

PS:如果Block带返回值的情况下,Block是这样定义和调用的

//定义block
typealias fucBlock = (backMsg :String) ->(String)
//函数内回调
process.processWithBlock("bbb") { (backMsg) ->(String) in
print(backMsg)
return "get msg"

2.3.刚使用的typealias把block给定义给一个变量了,现在直接代替进去就可以了,并且我给函数再加个String类型返回值。。

processData.swift

func processWithBlock(cmdStr:String?,blockProperty:(backMsg :String) ->())->(String){
blockProperty(backMsg :"backMsg---by block inside func")
return ""
}

swift:https://github.com/rayshen/SwiftClosure

oc:https://github.com/rayshen/callbackDemo

Swift 用Delegate和Block实现回调的Demo的更多相关文章

  1. iOS 键盘添加完成按钮,delegate和block回调

    这个是一个比较初级一点的文章,新人可以看看.当然实现这个需求的时候自己也有一点收获,记下来吧. 前两天产品要求在工程的所有数字键盘弹出时,上面带一个小帽子,上面安装一个“完成”按钮,这个完成按钮也没有 ...

  2. iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)

    iOS页面间传值实现方法:1.通过设置属性,实现页面间传值:2.委托delegate方式:3.通知notification方式:4.block方式:5.UserDefault或者文件方式:6.单例模式 ...

  3. iOS页面间传值的方式(NSUserDefault/Delegate/NSNotification/Block/单例)

    iOS页面间传值的方式(NSUserDefault/Delegate/NSNotification/Block/单例) 实现了以下iOS页面间传值:1.委托delegate方式:2.通知notific ...

  4. 【转】iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)-- 不错

    原文网址:http://www.cnblogs.com/JuneWang/p/3850859.html iOS页面间传值的方式(NSUserDefault/Delegate/NSNotificatio ...

  5. iOS页面间传值的方式 (Delegate/NSNotification/Block/NSUserDefault/单例)

    iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)   iOS页面间传值的方式(NSUserDefault/Delegate/NSN ...

  6. iOS页面间传值的五种方式总结(Delegate/NSNotification/Block/NSUserDefault/单例)

    iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例) iOS页面间传值的方式(NSUserDefault/Delegate/NSNot ...

  7. block学习二:使用Block替代回调

    使用Block替代回调,分为三步进行:

  8. iOS 传值 委托(delegate)和block 对比

     技术交流新QQ群:414971585 这篇文章建议和前一篇一起看, 另外先弄清楚IOS的block是神马东东. 委托和block是IOS上实现回调的两种机制.Block基本可以代替委托的功能,而且实 ...

  9. [Objective-C] Block实现回调和简单的学习思考

    初识Block的时候,总觉得其很可怕,因为看不懂其运行原理,所以用起来总是觉得不安全.关于Block的语法,等我把手里的资料全部看完,整理好再发出来.这次先看看用Block怎么实现回调. 新博客:wo ...

随机推荐

  1. 利用performance属性查看网页性能

    一般我们可以通过浏览器的调试工具-网络面板,或者代理工具查看网页加载过程中的各个阶段的耗时.而利用window.performance属性则可以获得更为精确的原始数据,以毫秒为单位,精确到微秒. pe ...

  2. express:webpack dev-server中如何将对后端的http请求转到https的后端服务器中?

    在上一篇文章(Webpack系列:在Webpack+Vue开发中如何调用tomcat的后端服务器的接口?)我们介绍了如何将对于webpack-dev-server的数据请求转发到后端服务器上,这在大部 ...

  3. ICSharpCode.SharpZipLib

    ICSharpCode.SharpZipLib 压缩.解压文件 附源码   http://www.icsharpcode.net/opensource/sharpziplib/ 有SharpZipli ...

  4. FineUI小技巧(3)表格导出与文件下载

    需求描述 实际应用中,我们可能需要导出表格内容,或者在页面回发时根据用户权限下载文件(注意,这里的导出与下载,都是在后台进行的,和普通的一个链接下载文件不同). 点击按钮导出表格 由于FineUI 默 ...

  5. The superclass javax.servlet.http.HttpServlet was not found on the Java Build Path。

    项目上右键-->Build Path-->Configuration Build Path -->Add Library -->Server Runtime 选择tomcat

  6. iOS 隐藏/去掉 导航栏返回按钮中的文字

    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(, -) forBarMetrics:U ...

  7. Collection中list集合的应用常见的方法

    集合 : 用存放对象的容器(集合)     Collection : 跟接口 : 单列集合          ---> List :有序的 ,元素是可以重复的.          ---> ...

  8. android 监听短信并发送到服务器

    1. 接受系统的短信广播,操作短信内容. 优点:操作方便,适合简单的短信应用. 缺点:来信会在状态栏显示通知信息. 2. 应用观察者模式,监听短信数据库,操作短信内容.   实例如下: SystemE ...

  9. BIM软件小技巧:Revit2014所有快捷键汇总表格

    命令 快捷键 路径 修改 MD 创建>选择;  插入>选择; 注释>选择; 视图>选择; 管理>选择; 修改>选择; 建筑>选择; 结构>选择;  系统 ...

  10. 高手详解SQL性能优化十条经验

    1.查询的模糊匹配 尽量避免在一个复杂查询里面使用 LIKE '%parm1%'—— 红色标识位置的百分号会导致相关列的索引无法使用,最好不要用. 解决办法: 其实只需要对该脚本略做改进,查询速度便会 ...