Swift 'self'在'super.init'调用之前使用,当尝试使用委托时

pkwftd7m  于 2023-03-22  发布在  Swift
关注(0)|答案(1)|浏览(137)

当我尝试在init方法中使用CBPeripheralManagerDelegate时,我在'super.init'错误之前使用了'self'。

import CoreBluetooth
        
        @objc
        public class L2CapChannelManager : NSObject, CBPeripheralManagerDelegate {
               
            private var peripheralManager: CBPeripheralManager?
            private var deviceConnectedMethodChannel: FlutterMethodChannel
            
            @objc
            public init(deviceConnectedMethodChannel: FlutterMethodChannel) {
                self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
                self.deviceConnectedMethodChannel = deviceConnectedMethodChannel
            }
bvjxkvbb

bvjxkvbb1#

在你的对象完全初始化之前,你将self传递给CBPeripheralManager的初始化器。如果你将代码改为这样,它将编译:

import CoreBluetooth
        
@objc
public class L2CapChannelManager : NSObject, CBPeripheralManagerDelegate {
               
    private var peripheralManager: CBPeripheralManager?
    private var deviceConnectedMethodChannel: FlutterMethodChannel
            
    @objc
    public init(deviceConnectedMethodChannel: FlutterMethodChannel) {
        self.deviceConnectedMethodChannel = deviceConnectedMethodChannel
        super.init()
        self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    }
}

另一种解决方案是通过使用lazy属性来延迟CBPeripheralManager的创建:

import CoreBluetooth
        
@objc
public class L2CapChannelManager : NSObject, CBPeripheralManagerDelegate {
               
    private lazy var peripheralManager: CBPeripheralManager? = {
        CBPeripheralManager(delegate: self, queue: nil)
    }()
    private var deviceConnectedMethodChannel: FlutterMethodChannel
            
    @objc
    public init(deviceConnectedMethodChannel: FlutterMethodChannel) {
        self.deviceConnectedMethodChannel = deviceConnectedMethodChannel
    }
}

相关问题