如何使用台风快速注入代表?

时间:2016-02-28 02:20:08

标签: ios swift typhoon

使用台风我试图在我的视图控制器中注入“worker”类型。我的“工人”需要一个委托,这样当工作完成后,它会调用这个方法。我需要将我的视图控制器设置为注入的worker类的委托。换句话说,循环依赖。

使用来源更新了问题:

//my typhoon assembly class
import Typhoon
class Assembly : TyphoonAssembly {

    public dynamic func viewController() -> AnyObject {
        return TyphoonDefinition.withClass(ViewController.self) {
            (definition) in

            definition.injectProperty("worker", with: self.foo())
            definition.scope = TyphoonScope.Singleton
        }
    }


    public dynamic func foo() -> AnyObject {
        return TyphoonDefinition.withClass(Foo.self) {
            (definition) in

            definition.injectProperty("delegate", with: self.viewController())
        }
    }

}

Foo是完成工作的地方,它实现了WorkHandler协议,并且在工作完成时有一个类型为SomeProtocol的委托:

import Foundation

@objc
protocol SomeProtocol: class {
    optional func hasFinishedWork(value: Bool)
}

protocol WorkHandler : class {
    func doSomething()
}



class Foo: WorkHandler{

    //how will this get set?
    var delegate:SomeProtocol?

    func doSomething(){
        print("doing the work")
        delegate?.hasFinishedWork!(true)
    }
}

我的ViewController符合SomeProtocol,如下所示:

import UIKit

class ViewController: UIViewController, SomeProtocol{

    var worker:WorkHandler?

    override func viewDidLoad() {
        super.viewDidLoad()

        worker?.doSomething();
    }

    @objc func hasFinishedWork(value: Bool){
        print("The work was all done")
    }
}

上面的代码在运行时会出现以下错误:

2016-02-29 20:25:43.250 TestApp[30604:5316415] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Subclass of NSProxy or NSObject is required.'

有人能够帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

原来我必须让我的协议继承自NSObject:

@objc
protocol SomeProtocol: class {
    optional func hasFinishedWork(value: Bool)
}

@objc
protocol WorkHandler : class {
    func doSomething()
}




class Foo: NSObject, WorkHandler{

    //how will this get set?
    var delegate:SomeProtocol?

    @objc func doSomething(){
        print("doing the work")
        delegate?.hasFinishedWork!(true)
    }
}

现在它按预期工作。