【问题标题】:Class with custom delegate具有自定义委托的类
【发布时间】:2017-09-13 13:21:24
【问题描述】:

我正在一个类中创建一个自定义委托并尝试在我的控制器中实现该协议。 但是没有作为代表工作是零。 我就是这样做的:

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.")
    } 
}

我也尝试过创建一个类对象并在 viewDidLoad 中分配BluetoothOperations's object. getWatchCollectedData = self,但没有成功。

知道我在哪里做错了吗? 谢谢。

【问题讨论】:

  • BluetoothOperations 的对象。 getWatchCollectedData = 自我
  • 也试过了。但没有用。 @HarshalValanda
  • 你的BluetoothOperations 对象是全局对象吗? ,或者展示你是如何创建实例的
  • 让 object = BluetoothOperations(), object.getWatchCollectedData = self
  • @JonSnow 是的,它是全球性的。更新问题。

标签: ios swift delegates


【解决方案1】:

您的代码看起来正确。这是它可能失败的一个可能原因。在您的 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.")
    } 
}

【讨论】:

  • 好的,我按照你说的做了,该函数正在从 viewDidLoad 中调用。
  • @sharadchauhan。好的。这意味着您的委托系统工作正常。事情出错了,正如我所说的那样。未在您正在运行的实际 BluetoothOperations 对象上设置委托。所以请确保从你的控制器初始化的BluetoothOperations对象和委托设置正确。
  • @sharadchauhan 是的,这是问题所在,您的 customFunc 不是从您从 SomeController 创建的实例中调用的
  • @JonSnow 是的。我该怎么做才能实现它?
  • @sharadchauhan 好吧,这取决于您的代码运行BluetoothOperations 实例的方式、位置和时间。您可以尝试从 BluetoothOperations 类创建一个单例对象,并确保没有重复的实例。
【解决方案2】:

你已经正确实现了委托,但没有在正确的类之间实现

当您在SomeController 和其他视图控制器中创建BluetoothOperations 的对象时,比如说SomeController1

现在委托只负责相关的类

喜欢

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

而你正在尝试这样

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

这种方式是做不到的,

因为您的 SomeController1SomeController 没有从任何地方连接

很难给你建议一个答案

您在 SomeController1SomeController 两者之间创建委托。

希望你清楚

【讨论】:

    猜你喜欢
    • 2017-04-09
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多