1

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

1 回答 1

4

您将您的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];
    }
}
于 2015-03-10T21:38:14.103 回答