SWift开发:使用委托/Protocol 实现类之间的数据传递
在iOS中委托的实现,需要使用protocol关键字,使用委托可以实现类之间的数据传递,比如,我有个类,用于返回数据,当我生成数据后,将数据自动反馈给主类,这和socket通信很像是不是,哈哈,开始上代码。 1 创建一个swift文件 ,内容如下:import UIKit protocol WorkDelegate: NSObjectProtocol { /*委托方法*/ func didPrint(testDelegate: TestDelegate,str:String) } public class TestDelegate : NSObject { let ID: Int? init(id:Int) { ID = id } /*定义委托,使用weak,避免循环强引用 */ weak var delegate: WorkDelegate? /*触发委托事件*/ func didWorkDelegate(str:String) { delegate?.didPrint(self,str: str) } }
2 在主类里使用,代码如下:
import UIKit class ViewController: UIViewController,WorkDelegate { var test: TestDelegate! /* 添加一个按钮,执行TestDelegate里的调用委托的方法*/ @IBAction func startDelegate(sender: AnyObject) { test?.didWorkDelegate("hello delegate or protocol ! ") } override func viewDidLoad() { super.viewDidLoad() test = TestDelegate(id: 1) test.delegate = self } /* 委托里的方法 */ func didPrint(testDelegate: TestDelegate,str: String) { print("main:" + str) print(testDelegate.ID!) } } 3 效果图
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |