美文网首页
Swift - Protocol&Delegate 露易

Swift - Protocol&Delegate 露易

作者: AltriaKassem | 来源:发表于2016-01-01 23:41 被阅读183次

//看门狗经典场景解释代理委托机制

//

//  ViewController.swift

//  ProtocolDelegate

//

//  Created by sz on 16/1/1.

//  Copyright (c) 2016年 sz. All rights reserved.

//

import UIKit

//自定义一个协议

protocol HouseSecurityDelegate {

func handleIntruder()

}

//持有遵守协议者(代理人)的主人

class House: NSObject {

var delegate:HouseSecurityDelegate?

var name:String?

func burglarDetected()

{

print("im " + name!)

println(" i need a dog")

delegate?.handleIntruder()

}

}

//代理方--才狗! 汪汪 !(注意Swift遵守协议是继承语法,是冒号)

//看门狗类继承了NSObject,HouseSecurityDelegate

//Swift在你对协议的必选方法未实现时会报错(does not conform to)

class GuardDog: NSObject,HouseSecurityDelegate {

//遵守原则,谁继承,谁实现方法

func handleIntruder() {

println("614 im saito")

}

}

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

let myhouse = House()

myhouse.name = "louise"

myhouse.burglarDetected()

let saito = GuardDog()

myhouse.delegate = saito

myhouse.burglarDetected()

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

相关文章

  • Swift - Protocol&Delegate 露易

    //看门狗经典场景解释代理委托机制 // // ViewController.swift // ProtocolD...

  • swift delegate 和 block 使用

    swift delegate 和 block 使用 delegate使用 //自定义cell 代码importUI...

  • delegate

    Swift的delegate 用weak修改的时候的注意事项Swift-代理

  • Swift小知识

    1. 关于Swift中Protocol 1. 在 Swift 中,Delegate 就是基于 Protocol 实...

  • swift delegate

  • Swift delegate

    ARC 中,对于一般的 delegate,在声明中将其指定为 weak,在这个 delegate 实际的对象被释放...

  • Swift - Delegate

    在ARC中,对于一般的delegate,我们会在声明中将其指定为weak,在这个delegate实际的对象被释放的...

  • About iOS programming: Delegate

    关于Delegate设计模式. From Hacking with Swift, Project 4. Deleg...

  • swift delegate 使用

    1、声明一个deleagte @objc protocol MVPTabBarDelegate : NSObjec...

  • Swift weak delegate

    需要使用delgate时,为了防止循环引用需要添加weak关键字,但是上面的代码XCode会报错。因为swift里...

网友评论

      本文标题:Swift - Protocol&Delegate 露易

      本文链接:https://www.haomeiwen.com/subject/sjdwhttx.html