【问题标题】:CBCentralManagerDelegate not gets call in NSObjectCBCentralManagerDelegate 没有在 NSObject 中被调用
【发布时间】:2015-05-12 10:28:29
【问题描述】:

我创建了一个继承自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;

【问题讨论】:

    标签: ios objective-c core-bluetooth cbcentralmanager


    【解决方案1】:

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

    您需要将实例存储在调用类中的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];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2016-10-12
      • 2019-08-14
      相关资源
      最近更新 更多