本文介绍了如何符合CBCentralManagerDelegate协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化中央管理器实例,以使应用程序具有蓝牙连接.

I am trying to initialize a central manager instance to make an app with Bluetooth connectivity.

这是我的代码的一部分:

This is part of my code:

class ViewController: UIViewController, CBCentralManagerDelegate {
   var myCentralManager = CBCentralManager(delegate: self, queue: nil) //error on this line
   func centralManagerDidUpdateState(central: CBCentralManager!) { 
}

我得到一个错误:

协议唯一需要的方法是我添加的centralManagerDidUpdateState(),为什么会出现错误?

The only method required by the protocol is centralManagerDidUpdateState() which I have added, so why do I get an error?

推荐答案

该错误消息有些欺骗性,使您远离实际问题.问题在于您正在访问初始化器中的self来获取存储的属性,而您不能这样做.

The error message is a little deceiving and is pointing you away from the actual issue. The problem is that you are accessing self in the initializer for a stored property, which you can't do like this.

一种解决方法是简单地声明属性而不对其进行初始化,然后将对变量的赋值移动到某个位置,例如用于视图控制器的初始化程序,或将视图控制器的生命周期方法之一(例如viewDidLoad).

One workaround is to simply declare the property without initializing it, and then move the assignment to the variable to somewhere like an initializer for your view controller, or one of your view controller's lifecycle methods, like viewDidLoad.

这篇关于如何符合CBCentralManagerDelegate协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:02