2017-09-13 54 views
3

我正在类中创建一个自定义委托并试图在我的控制器中实现该协议。 但是因为委托没有工作,所以没有工作。 这是我正在做它:带自定义代理的类

BluetoothOperations.swit

protocol GetWatchCollectedData:NSObjectProtocol { 
    func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData) 
} 

class BluetoothOperations: NSObject{ 
    var getWatchCollectedData: GetWatchCollectedData? 

    func customFunc(){ 
     getWatchCollectedData.getWatchCollectedData(ID,Data) 
    } 
} 

SomeController.swift

class SomeController: UIViewController { 
    let object = BluetoothOperations() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     object.getWatchCollectedData = self 

    } 
} 

extension SomeController: GetWatchCollectedData{ 
    func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData){ 
     print("delegate working.") 
    } 
} 

我也试图使类的一个对象,并指定BluetoothOperations's object. getWatchCollectedData = self在viewDidLoad中,但没有工作。

任何想法,我做错了吗? 谢谢。

+0

BluetoothOperations的对象。 getWatchCollectedData = self –

+0

也尝试过。但没有工作。 @HarshalValanda –

+0

你的'BluetoothOperations'对象是全局对象吗? ,或者显示如何创建实例 –

回答

2

您的代码看起来正确。这是它可能失败的一个可能的原因。在您的SomeController中,您正在从BluetoothOperations类中创建object并正确分配了委托。

但是,您必须确保您的控制器中定义的对象正在发出委托调用。您可能会有BluetoothOperations的另一个实例,并且实际上正在使用该实例,并且在该实例中,代理未设置。

检查此问题的最简单方法是手动触发您在视图控制器中创建的对象中的委托。尝试下面的代码来查看委托是否被触发。

class SomeController: UIViewController { 
    let object = BluetoothOperations() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     object.getWatchCollectedData = self 
     object.customFunc()// Trigger the delegate function here 
    } 
} 

extension SomeController: GetWatchCollectedData{ 
    func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData){ 
     print("delegate working.") 
    } 
} 
+0

好吧,我做了你所说的,并且该函数正从viewDidLoad调用。 –

+0

@sharadchauhan。好的。这意味着您的代理系统工作正常。事情出了问题就和我说的一样。代表未在您正在运行的实际'BluetoothOperations'对象上设置。所以请确保从您的控制器初始化的'BluetoothOperations'对象和委托设置正确。 –

+0

好,可能的解决方案是? –

1

您正确实施,但不正确的类

正如你在SomeController,并在其他浏览器让我们说SomeController1

创建的BluetoothOperations对象之间的委托现委托只负责相关类别

like

`BluetoothOperations` (Call `customFunc`)  ----> `SomeController1` 
`BluetoothOperations` (Call `customFunc`) ----> `SomeController` 

,且您尝试这样

`SomeController1 ---> `BluetoothOperations` (Call `customFunc`) ----> SomeController` 

这不能用这种方式可以实现,

当你的SomeController1SomeController不是从任何地方

连接是非常困难建议您回答

您可以在SomeController1SomeController之间创建代表。

希望你很清楚