我正在尝试使用CoreBluetooth框架,并且我已经创建了一个帮助程序类(btHelper),以使代码更易于维护等。
问题在于,在这个帮助器类中,委托方法不再被调用,就像它们最初被刷成大类时一样。是的我在helper类的.h中设置了委托方法,是的,我已将对象CBCentralManager委托设置为self。我几乎完成了所有事情,就像在一堂课中一样。 我认为它与主线程有关,但我对此没什么经验。
具体来说,我想要的委托方法是
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
任何人都可以告诉我,为了让委托调用在这个助手类中应该工作,我必须做些什么? 谢谢!
以下是PrimaryViewController类和btHelper类
btHelper.m
-(void) activateBluetooth
{
self.manager= [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//DELEGATE METHOD THAT NEVER GETS CALLED. SHOULD BE CALLED AS SOON AS self.manager is initiated
self.isAvailable=FALSE;
switch (central.state) {
case CBCentralManagerStatePoweredOff:
NSLog(@"CoreBluetooth BLE hardware is powered off");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
self.isAvailable=TRUE;
break;
case CBCentralManagerStateResetting:
NSLog(@"CoreBluetooth BLE hardware is resetting");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"CoreBluetooth BLE state is unauthorized");
break;
case CBCentralManagerStateUnknown:
NSLog(@"CoreBluetooth BLE state is unknown");
break;
case CBCentralManagerStateUnsupported:
NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
break;
default:
break;
}
}
PrimaryViewController.m
-(IBAction)connect
{
btHelper *bluetoothManager= [[btHelper alloc]init];
[bluetoothManager activateBluetooth];
}
答案 0 :(得分:13)
你的帮助器实例是-connect
方法中的局部变量。
因此ARC在您可以接收委托方法之前释放它(以及CBCentralManager实例)。
让你的助手成为PrimaryViewController的实例变量(或属性),这将解决你的问题。
@interface PrimaryViewController : UIViewController
{
// BTHelper instead of btHelper, to follow naming convention
BTHelper *_bluetoothManager;
}
@end
@implementation PrimaryViewController
-(IBAction)connect
{
// FIXME: this don't check if _bluetoothManager is already instantiated
_bluetoothManager = [[BTHelper alloc] init];
[_bluetoothManager activateBluetooth];
}
@end
答案 1 :(得分:0)
确保您的btHelper.m采用CBCentralManagerDelegate协议。
@interface btHelper () <CBCentralManagerDelegate> {}
在上述情况下,您很可能没有使用该方法出现任何错误:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
因为在几个版本之前,编译器停止要求您声明任何私有方法(在.m文件的接口部分中)。
希望这有帮助。