为什么不调用iOS中的自定义委托

时间:2015-03-13 06:07:49

标签: ios swift delegates swift-playground

我正在尝试使用swift中的playground创建自定义委托。但是, doSomething 方法未通过回调调用。 似乎 委托?.doSomething() 不会触发 XYZ doSomething 方法。 提前致谢!

import UIKit

@objc protocol RequestDelegate
{
    func doSomething();

      optional  func requestPrinting(item : String,id : Int)
}


class ABC
{
    var delegate : RequestDelegate?
     func executerequest() {

        delegate?.doSomething()
        println("ok delegate method will be calling")
    }
}   

class XYZ : RequestDelegate
{  
    init()
    {
        var a  = ABC()
        a.delegate = self
    }

     func doSomething() {
       println("this is the protocol method")
    }
}    

var a = ABC()
a.executerequest()

1 个答案:

答案 0 :(得分:7)

  

delegate?.doSomething()似乎没有激发到XYZ类   doSomething方法。

这是正确的。 class ABC具有可选的delegate属性,但值为。{ 该物业无处可寻。所以delegatenil 因此可选链接

delegate?.doSomething()

什么都不做。你也定义了一个class XYZ但是 没有创建该类的任何实例。

如果您将a的委托设置为XYZ的实例,那么 它将按预期工作:

var a = ABC()
a.delegate = XYZ()
a.executerequest()