CBCentralManagerDelegate无法在NSObject中调用

时间:2015-03-10 19:57:19

标签: ios objective-c core-bluetooth cbcentralmanager

我创建一个继承自NSObject的类,并添加delegate方法。在我的课堂上,我想使用CBCentralManager及其委托方法。但是委托方法没有得到调用。这是我的代码 -

这是VZBluetooth.h

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>

@protocol BluetoothDelegate <NSObject>

@required
-(void)getBluetoothStatus:(NSString*)status;

@end

@interface VZBluetooth : NSObject<CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong) id<BluetoothDelegate> delegate;
-(void)callBluetooth;

@end

对于VZBluetooth.m

@implementation VZBluetooth
{
    NSString *status;
    CBCentralManager *ce;

}
@synthesize delegate = _delegate;

-(void)callBluetooth
{
    ce = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

#pragma mark - Bluetooth Delegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{

    if(central.state == CBCentralManagerStatePoweredOn){
        if ([central respondsToSelector:@selector(scanForPeripheralsWithServices:options:)]) {
            status = CASE_STATUS_PASS;
        }
        else{
            status = CASE_STATUS_FAIL;
        }

    }
    else{
        status = CASE_STATUS_FAIL;
    }

    if ([self.delegate respondsToSelector:@selector(getBluetoothStatus:)]) {
        [self.delegate getBluetoothStatus:status];
    }
}

我的电话 -

VZBluetooth *blu = [[VZBluetooth alloc]init];
[blu callBluetooth];
blu.delegate = self;

1 个答案:

答案 0 :(得分:3)

您正在将VZBluetooth实例分配为本地变量 - 因此只要该函数退出,它就会被释放。这几乎肯定是在蓝牙功能初始化之前,并有机会调用委托方法。

您需要将实例存储在调用类的strong属性中。

其他一些建议,delegate中的VZBluetooth属性应为weak而不是strong,以防止保留周期,您可以简化centralManagerDidUpdateState方法相当 -

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{

    status=CASE_STATUS_FAIL;

    if(central.state == CBCentralManagerStatePoweredOn){
        if ([central respondsToSelector:@selector(scanForPeripheralsWithServices:options:)]) {
            status = CASE_STATUS_PASS;
        }
    }
    if ([self.delegate respondsToSelector:@selector(getBluetoothStatus:)]) {
        [self.delegate getBluetoothStatus:status];
    }
}