CBCentralManagerDelegate 未在 NSObject 中调用

CBCentralManagerDelegate not gets call in NSObject

我创建了一个继承自 NSObject 的 class 并添加了 delegate 方法。在我的 class 中,我想使用 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;

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

您需要在 class.

中将实例存储在 strong 属性 上

一些其他建议,您在 VZBluetooth 中的 delegate 属性 应该是 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];
    }
}